简体   繁体   中英

While loop won't repeat

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"?

again is an empty string on first check, so the while is not executed at all. You are looking for a do .. while construct.

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.

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM