Learning Java in school currently and writing the classic “guess a number” game. I have to add an additional option to quit out mid-program, but am a little stuck on how to properly add that ability? I’m mostly confused on how I’d be able to do this given the scanner is asking for an int, where I want the string “quit” to allow the user to exit.
import java.util.Scanner;
import java.util.Random;
public class NumberGuesser {
public static void playGuess() {
// method created to run all the game logic when the main method calls it
Random rand = new Random();
Scanner sc = new Scanner(System.in);
int answer = rand.nextInt(50 - -50 + 1) + -50;
int totalGuesses = 1;
// storing random + input + guess count
while (true) {
// while loop to run while method is called + random excluded to not create new one each guess
System.out.println("Please enter a number between -50 and 50.");
int guess = sc.nextInt();
if (guess > 50 || guess < -50) {
// incorrect entry handling first (does not add to count if incorrect)
System.out.println("Incorrect entry.");
} else if (guess == answer) {
// correct answer check + break
System.out.println("Correct! It took you " + totalGuesses + " guesses.");
break;
} else if(guess < answer) {
// if guess is less than + adds to count
System.out.println("The number is higher.");
totalGuesses++;
} else if(guess > answer) {
// if guess is more than + adds to count
System.out.println("The number is lower.");
totalGuesses++;
}
}
}
public static void main (String[]args) {
// main method to call the game + prompt to play again
boolean playAgain = true;
do {
// call game when user input is y + ends program if not
playGuess();
System.out.println("Would you like to play again? Y/N.");
Scanner sc = new Scanner(System.in);
String answer = sc.nextLine();
playAgain = answer.equalsIgnoreCase("y");
} while (playAgain);
}
}
esperlark is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.