How to exit Java loop? While-loop in a basic guessing game

妖精的绣舞 提交于 2019-12-04 03:24:13

问题


I am trying to write a little game, but have stuck on how to prompt the user if they want to play again and how to exit the loop if they don't want to play again...

import java.util.Random;
import java.util.Scanner;

public class Guessinggame {

public static void main(String[] args) {

    System.out.println("Welcome to guessing game! \n" + " You must guess a number between 1 and 100. ");

    while (true) {

        Random randomNumber = new Random();
        Scanner g = new Scanner(System.in);

        int number = randomNumber.nextInt(100) + 1;
        int guess = 0;
        int numberOfGuesses = 0;

        while (guess != number){

            System.out.print("Guess: ");
            guess = g.nextInt();

            if (guess > number ){
                System.out.println( "You guessed too high!");
            }else if (guess < number ){
                System.out.println( "You guessed too low!");
            }else{
                System.out.println( "Correct! You have guessed "+ numberOfGuesses + " times. \nDo you want to play again? (y/n)  ");

            }
            numberOfGuesses++;


        }
    }
}

}


回答1:


You can use break to get out of the current loop.

for (int i = 0; i < 10; i++) {
  if (i > 5) {
    break;
  }
  System.out.Println(i);
}

Prints:

0
1
2
3
4
5

However, a do-while loop is probably better for your use case.




回答2:


Change

while(true){
  //At some point you'll need to 
  //exit the loop by calling the `break` key word
  //for example:

  if(/*it's not compatible with your condition*/)
    break;
}

to

boolean userWantsToPlay=true;
do{
   //the same as before
} while (userWantsToPlay);

then ask the user somewhere if they still want to play and set this variable to false if not.

The other solution is to keep your code as it is and just call break; after you ask the user and they say they don't want to continue, this just jumps out of the current loop and resumes at the first point after the loop. This is less preferred because it can be harder to trace the program flow as you read the code, especially if you start to have nested loops or multiple break points.




回答3:


You can change while(true) statement with do while statement.

Scanner k= new Scanner(System.in);

do{
// do sth here...

//ask to user for continue or exit
System.out.println("Continue/Break");
String answer = k.next();

}while(answer.equals("Continue"));

If you want to exit the loop you can use break statement.



来源:https://stackoverflow.com/questions/20099928/how-to-exit-java-loop-while-loop-in-a-basic-guessing-game

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!