【发布时间】:2021-06-15 21:18:45
【问题描述】:
我是一个制作猜谜游戏的初学者,我试图让玩家通过猜测 -1 来退出游戏。目前,如果我输入 -1,它会显示太低并要求我继续猜测,玩家在猜到数字之前无法退出游戏。
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char choice;
do {
int randomNum = (int) (Math.random() * 100 + 1);
int guess = 0;
while (guess != randomNum) {
System.out.println("Guess a number between 1-100");
guess = scan.nextInt();
if (guess > randoomNum) {
System.out.println("Too high.");
}
else if (guess < randoomNum) {
System.out.println("Too low.");
}
else if (guess > 0) {
System.exit(0);
System.out.println("GAME OVER");
System.out.println("the number was " + randomNum + ".");
}
else {
System.out.println("Correct! Well done!");
}
}
System.out.println("\nPlay again? (Y/N)");
choice = scan.next() .charAt(0);
} while (choice == 'Y' | choice =='y');
System.out.println("GAME OVER");
}
【问题讨论】:
-
在
guess = scan.nextInt();之后添加if (guess == -1) break; -
@JohnnyMopp,它似乎应该打破嵌套循环,或者可能使用
System.exit() -
@AlexRudenko 好的。然后他们应该将
else if (guess > 0)块中的内容移动到我拥有break的位置。所以,真的只是在他们得到用户输入后将整个块向上移动。无论如何,它应该是else if (guess < 0)。错字? -
@JohnnyMopp 谢谢!
-
在最后的 while 中,你应该使用逻辑或 ("||") 而不是位或。