This game is pretty common for beginner projects. I wrote a version of this before all in Main - so here I challenge myself to recreate it in a more OO style.
I wanted to take a more OO approach, so any feedback on where I could do better or am making some errors is appreciated. I also have some personal confusion if in some parts I'm coding this procedurally. I might be mistaken but I think this code is a bit of both styles, and if so, can someone help explain the distinctive differences? Is there too much recursion in some parts? How does the readability appear? What are your thoughts?
The game will generate a random secret number and ask the user to input their guesses within the given number of attempts Code below:
import java.util.InputMismatchException; import java.util.Random; import java.util.Scanner; public class GuessGame { private static final Scanner SC = new Scanner(System.in); private static final Random R = new Random(); private static int secret = R.nextInt(100) + 1; private static final int GIVEN_ATTEMPTS = 10; private int attempts = 0; public void playGame() { promptGuess(); } private int promptGuess() { try { printLine("Guess a number from 1-100"); int guess = SC.nextInt(); if (guess < 1) { promptGuess(); } else { return compare(guess); } } catch(InputMismatchException e) { printLine("Only numbers please"); SC.nextLine(); promptGuess(); } return 0; } private int compare(int guess) { attempts++; if (attempts == GIVEN_ATTEMPTS) { return promptResult(4); } int difference = secret - guess; if (difference > 0) { return promptResult(1); } else if (difference < 0) { return promptResult(2); } else { return promptResult(3); } } private int promptResult(int n) { switch (n) { case 1: printLine("Guess was too low, try again"); promptGuess(); break; case 2: printLine("Guess was too high, try again"); promptGuess(); break; case 3: printLine("You got it! Nice guess! The number was " + secret); printLine("In " + attempts + " attempts"); printLine("Game Over"); attempts = 0; secret = R.nextInt(100) + 1; playAgain(); case 4: printLine("Too many guesses! " + GIVEN_ATTEMPTS + "/" + GIVEN_ATTEMPTS + " used."); printLine("Secret number was: " + secret + " Game Over"); attempts = 0; secret = R.nextInt(100) + 1; playAgain(); } return 0; } private void printLine(String s) { System.out.println(s); } private void playAgain() { printLine("Play again? (Enter Y for yes or N for no)"); String reply = SC.next(); if (reply.equalsIgnoreCase("Y")) { playGame(); } else if (reply.equalsIgnoreCase("N")) { printLine("Thanks for playing"); System.exit(0); } else { System.out.println("Please enter a valid answer"); playAgain(); } } } public class Main { public static void main(String[] args) { GuessGame g = new GuessGame(); g.playGame(); } }