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

时间:2013-11-20 15:25:13

标签: 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++;


        }
    }
}

}

3 个答案:

答案 0 :(得分:12)

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

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

打印:

0
1
2
3
4
5

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

答案 1 :(得分: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;
}

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

然后询问用户是否还想玩,如果没有,请将此变量设置为false

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

答案 2 :(得分:0)

您可以使用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语句。