扫描输入并再次启动循环或关闭循环



我编程了一个猜测游戏,现在我遇到了一个问题。我想问用户他/她是否想再次玩游戏,如果答案是"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;
}

最新更新