如何退出Java循环?在一个基本的猜谜游戏中循环

use*_*011 6 java loops while-loop

我正在尝试编写一个小游戏,但是如果他们想要再次玩游戏又如何提醒用户以及如果他们不想再次玩游戏则如何退出循环...

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++;


        }
    }
}
Run Code Online (Sandbox Code Playgroud)

}

Zac*_*tta 13

您可以使用break退出当前循环.

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

打印:

0
1
2
3
4
5
Run Code Online (Sandbox Code Playgroud)

但是,do-while循环可能更适合您的用例.


Ros*_*rew 5

更改

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;
}
Run Code Online (Sandbox Code Playgroud)

boolean userWantsToPlay=true;
do{
   //the same as before
} while (userWantsToPlay);
Run Code Online (Sandbox Code Playgroud)

然后问用户某处是否还想玩,false如果没有则设置此变量.

另一个解决方案是保持你的代码不变,只是break;在你询问用户并且他们说他们不想继续之后调用它,这只是跳出当前循环并在循环后的第一个点恢复.这不太受欢迎,因为在读取代码时可能更难跟踪程序流,特别是如果您开始使用嵌套循环或多个break点.