【问题标题】:How to exit Java loop? While-loop in a basic guessing game如何退出Java循环?基本猜谜游戏中的while循环
【发布时间】:2013-11-20 15:25:12
【问题描述】:

我正在尝试编写一个小游戏,但一直坚持如何提示用户是否想再次玩以及如何退出循环如果他们不想再次玩......

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


        }
    }
}

}

【问题讨论】:

  • 退出循环的最佳选择是使用'break'。因此,创建一个条件(如果)并检查用户是否想再次播放,如果没有,则返回 break

标签: java loops while-loop


【解决方案1】:

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

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

打印:

0
1
2
3
4
5

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

【讨论】:

    【解决方案2】:

    改变

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

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

    然后在某个地方询问用户是否还想玩,如果不想玩,则将此变量设置为false

    另一种解决方案是保持您的代码不变,并在您询问用户并且他们说他们不想继续之后调用break;,这只是跳出当前循环并在第一点恢复循环之后。 这不是首选,因为在您阅读代码时可能更难跟踪程序流程,尤其是当您开始有嵌套循环或多个break 点时。

    【讨论】:

      【解决方案3】:

      您可以将while(true) 语句更改为do while 语句。

      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"));
      

      如果要退出循环,可以使用break 语句。

      【讨论】:

        猜你喜欢
        • 2021-11-02
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 2015-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多