Reputation: 13
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Random r = new Random();
intro();
int numGames = 0;
int numGuesses = game(console, r);
int max = max(numGuesses);
String again = "";
while (again.startsWith("y") || again.startsWith("Y")) {
game(console, r);
System.out.println("Do you want to play again?");
again = console.next();
numGames++;
}
stats(numGames, numGuesses, max);
}
This is my code in my method main where the code is supposed to call to other methods to play a guessing game with numbers. I set up my while loop so that it will run the game and after the game is ran, it will ask the user if he/she would like to play again. The user would then type in anything and if the string he/she types starts with a "y" or a "Y" then the game would be played again. (Anything else, assuming the user doesn't type any other letter other than "n" or "N", then the program would go to the method call stats(); )
The problem is, after the game is ran once and the user guesses correctly, the program doesn't even ask to play again, it just goes straight to the stats(); method call. What am I doing wrong? How do i fix it so that it will ask the user to play again and will keep playing as long as the user types any word that starts with "y" or "Y"?
Upvotes: 0
Views: 2069
Reputation: 314
Looks like what console.next()
is producing is neither a 'y' nor a 'Y'. Have you tried printing what again
is before the end of the loop? Try dumping the contents (and not just the characters, but the length of the read value.
See How do you accept 1 or 2 string variable with console.next() in shortest code, Java?
Upvotes: 0
Reputation: 424983
Since again
is just a loop-scope variable, I would use a for loop:
for (String again = "y"; again.toLowerCase().startsWith("y"); again = console.next()) {
game(console, r);
numGames++;
System.out.println("Do you want to play again?");
}
Added a simplification of case checking too.
Upvotes: 0
Reputation: 6387
again
is an empty string on first check, so the while is not executed at all.
You are looking for a do .. while
construct.
Upvotes: 5
Reputation: 12805
You're initializing again
as an empty string. So when it hits your while
, it does not start with either. You'll want to use a do
/while
loop instead.
do {
// Same content as your other loop
} while (again.startsWith("y") || again.startsWith("Y"))
This will allow you to set the again
variable before trying to loop.
Upvotes: 2