I’m trying to write a very simple number guessing game (code is below). After 1 round is finished, the user is supposed to be able to decide whether he/she wants to play another round or not. Problem is, the program always skips the last question (never letting the user answer ‘y’ or otherwise. What am I missing here? Is there something about java.util.Scanner I don’t know about?
import java.util.Random;
import java.util.Scanner;
public class GuessNum {
public GuessNum() {
int numRandom = 0;
int numGuess;
int life = 5;
String want = "";
Random rand = new Random();
Scanner scan = new Scanner(System.in);
do {
int lifeLeft = 5;
numRandom = rand.nextInt(9)+1;
System.out.print("\nGuess the Number [1..10]\n");
System.out.print("===================\n");
System.out.print("You have " + lifeLeft + " chances.\n");
do {
do {
System.out.print("What number do I have in mind: ");
numGuess = scan.nextInt();
if (numGuess < 1 || numGuess > 10)
System.out.println("Invalid input. Range is 1-10.");
} while (numGuess < 1 || numGuess > 10);
if (numGuess != numRandom && lifeLeft != 0)
System.out.println("Wrong! You only have " + --lifeLeft + " chances left.");
} while (numGuess!=numRandom && lifeLeft > 0);
if (numGuess == numRandom)
System.out.println("Correct! -- in " + (life - lifeLeft) + " guess(es).");
if (lifeLeft == 0) {
System.out.println("You have no more lives..");
System.out.println("This is the number: " + numRandom);
}
System.out.print("\nEnter 'y' if you want to play again or any other character to exit: ");
want = scan.nextLine();
} while (want.equals("y") || want.equals("Y"));
}
public static void main(String[] args) {
new GuessNum();
}
}
Use
want = scan.next();instead ofnextLine().The reason for your problem is that following the preceding
nextInt(), you’re still on the same line, andnextLine()returns the rest of the current line.Here’s a smallest snippet to reproduce the behavior:
When you type in, say,
5and then hit Enter, the output is:That is,
nextLine()did not block for your input, because the current line still has an empty string remaining.For comparison, when you type in, say
5 yeah!and then hit Enter, then the output is:Note that
" yeah!"actually comes from the same line as the5. This is exactly as specified in the documentation:On half-open ranges
Assuming that the number to guess is between 1 and 10 inclusive, the following code is “wrong”:
Here’s an excerpt from the documentation of
java.util.Random:That is, like a lot of methods in Java’s API,
Random.nextInt(int)uses the half-open range, with inclusive lower bound and exclusive upper bound.Related questions