我正在尝试制作一个高低数字猜谜游戏,如果他们的猜测太高,太低或太准确,就会向用户报告。除了成功猜测(所有事情)之外,一切都按预期工作。输入正确的数字后,循环打印"您的猜测是正确的"声明以及尝试次数。这就是我想要的。但是,不是询问用户是否想要重播下一个,而是返回“太高”"响应。我是否错误地嵌套了这个?
import java.util.Scanner;
import java.util.Random;
public class hilo2 {
public static void main(String[] args) {
int guess = 0;
int attempts;
String quit;
boolean replay = true;
Scanner scan = new Scanner(System.in);
Random generator = new Random();
while (replay) {
attempts = 0;
int answer = generator.nextInt(101) + 1;
System.out.println(answer);//for testing
System.out.println("Guess a number between 1 and 100. Enter your guess (0 to quit): ");
guess = scan.nextInt();
scan.nextLine();
while (guess != 0){
if (guess < answer) {
System.out.println("You guess was too low. Guess again (0 to quit): ");
guess = scan.nextInt();
scan.nextLine();
attempts++;
}
else if (guess > answer) {
System.out.println("Your guess was too high. Guess again (0 to quit): ");
guess = scan.nextInt();
scan.nextLine();
attempts++;
}
else {
System.out.println("Your guess was correct!");
attempts++;
System.out.println("Number of guesses: " + attempts);
answer = 0;
}
}
System.out.println("Would you like to play again? (y/n): ");
String input = scan.nextLine();
if (input.equalsIgnoreCase("n")) {
replay = false;
}
}
}
}
答案 0 :(得分:0)
你有
while (guess != 0){
更改代码以打破循环
else {
System.out.println("Your guess was correct!");
attempts++;
System.out.println("Number of guesses: " + attempts);
answer = 0;
break; // add this or change above line to guess = 0;
}
答案 1 :(得分:0)
while (guess != 0) {
if (guess < answer) {
System.out.println("You guess was too low. Guess again (0 to quit): ");
guess = scan.nextInt();
scan.nextLine();
attempts++;
} else if (guess > answer) {
System.out.println("Your guess was too high. Guess again (0 to quit): ");
guess = scan.nextInt();
scan.nextLine();
attempts++;
} else {
System.out.println("Your guess was correct!");
attempts++;
System.out.println("Number of guesses: " + attempts);
answer = 0;
}
}
你没有把它嵌套错误,但你没有条件中止while
循环。
您将answer
设置为0,然后返回到while
循环的开头。发现猜测现在太高了,因为答案是0。
我想你想做guess = 0;
。或者你也可以在那里放break;
。