如何退出Java循环?基本猜谜游戏中的 while 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20099928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to exit Java loop? While-loop in a basic guessing game
提问by user2906011
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++;
}
}
}
}
}
回答by Zach Latta
回答by Ross Drew
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.
然后在某处询问用户是否还想玩并将此变量设置为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.
另一种解决方案是保持您的代码原样,并break;
在您询问用户并且他们说他们不想继续后调用,这只是跳出当前循环并在循环后的第一点继续。这不是首选,因为在阅读代码时跟踪程序流程可能会更困难,尤其是当您开始有嵌套循环或多个break
点时。
回答by Batuhan B
You can change while(true)
statement with do while
statement.
您可以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"));
If you want to exit the loop you can use break
statement.
如果要退出循环,可以使用break
语句。