我编写了一个猜谜游戏,现在遇到了问题。我想询问用户是否想再次玩,如果答案是“y”(是),则重新启动游戏,如果答案是“N”(否),则应该结束循环。
为什么我输入“否”就不会结束? 有人可以帮我解决这部分代码吗?
我尝试过不同的方法,例如在类外部或内部定义它等。
public class GuessingGame {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random rdm = new Random();// Welcome to the game
System.out.println("Welcome!");
// Generate random number
int input = 0;
do {
int rdmNumber = rdm.nextInt(999) + 1;
while (input != rdmNumber) {
try {
System.out.println("Please enter your guess:");
int userGuess = Integer.parseInt(sc.next());
input = userGuess;
} catch (NumberFormatException e) {
System.out.println("Not a number - try again!");
}
if (input > rdmNumber) {
System.out.println("Too big!");
} else if (input < rdmNumber) {
System.out.println("Too small!");
} else if (input == rdmNumber) {
System.out.println("You win!");
}
}
System.out.println("Play another Round? [y/N]");
String nextRound = sc.nextLine();
sc.next();
if (nextRound.contains("y")) {
input = 0;
}
}while (input == 0);
}
}
如果用户输入“y”,游戏就会重新启动,如果他/她输入“N”,游戏就会结束。
最佳答案
您仅在 nextRound.contains("y")
时更新input
。因此,对于“y”以外的任何输入,输入将保持 0
(您初始化的值)。 while 循环继续,因为 input == 0
为 true。
正确的解决方案是将您的 if
语句更改为:
if (nextRound.contains("N")) {
input = 1;
}
或者:
if (nextRound.contains("N")) {
return;
}
关于java - 扫描输入并再次开始循环或关闭它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58700413/