我尝试从http://www.abgamerguys.com/tutorials/java-for-beginners-tutorial-day-3/制作数字猜谜游戏,我决定添加自己的重播功能。
//Replay feature
boolean replay = true;
while (replay == true) {
System.out.print("Do you want to play again? (y/n) : ");
String askReplay = inputScanner.nextLine();
if (askReplay.equalsIgnoreCase("y")) {
playNumberGame = true;
replay = false;
} else if (askReplay.equalsIgnoreCase("n")) {
playNumberGame = false;
replay = false;
} else {
System.out.println("Unknown reply.");
}
}
问题是在我给出一个输入(y / n)之前运行的最后一个else语句然后它再次循环然后我能够给出一个输入并运行它应该的样子。
这是我得到的输出:
Do you want to play again? (y/n) : Unknown reply.
Do you want to play again? (y/n) :
完整代码here。
答案 0 :(得分:2)
可以肯定的是,你应该展示循环之前会发生什么。
答案 1 :(得分:0)
使用inputScanner.next();你会得到你想要的结果,就像这样
boolean replay = true;
while (replay == true) {
System.out.print("Do you want to play again? (y/n) : ");
String askReplay = inputScanner.next();
if (askReplay.equalsIgnoreCase("y")) {
playNumberGame = true;
replay = false;
} else if (askReplay.equalsIgnoreCase("n")) {
playNumberGame = false;
replay = false;
} else {
System.out.println("Unknown reply.");
}
}
答案 2 :(得分:0)
我刚试过它,这是一个简单的修复。
变化:
String askReplay = inputScanner.nextLine();
到
String askReplay = inputScanner.next();
无论由于空格或返回字符而已调用的行的状态, next()
都将等待。