我的目标:创建一个程序,可以检查您猜到的数字是否正确。它会告诉你它是否太高/太低。它需要继续给你机会,直到你猜对了。此外,如果您愿意,它需要能够在您完成后从头开始恢复。
问题:我的if语句卡在无限循环中,并且尝试在最后重新启动程序根本不起作用。
import java.util.Random;
import java.util.Scanner;
public class driver {
public static void main (String [] args) {
// Output number of guesses.
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(100) + 1;
System.out.println(randomInt);
System.out.println("Welcome to my guessing game. What is your first guess that is between 1 and 100?");
int userInput = scan.nextInt();
String playAgain = "Y";
int guesses = 0;
System.out.println(randomInt);
while (playAgain == "Y") {
if (userInput > 0 && userInput < 100) {
if (userInput == randomInt){
guesses++;
System.out.println ("Right! Guesses: " + guesses);
playAgain = "f";
}
// Too low
else if (userInput < randomInt) {
guesses++;
System.out.println ("Your guess was too LOW.");
}
// Too high
else {
System.out.println ("Your guess was too HIGH.");
guesses++;
}
}
}
// I want to be able to resume from the top if the user says Y.
System.out.println("Would you like to play again?(Y/N)");
playAgain = scan.next();
}
}
答案 0 :(得分:1)
最后两行应该在你的while循环中,问题在于你的大括号
while (playAgain == "Y") {
if (userInput > 0 && userInput < 100) {
if (userInput == randomInt){
guesses++;
System.out.println ("Right! Guesses: " + guesses);
playAgain = "f";
}
else if (userInput < randomInt) {
guesses++;
System.out.println ("Your guess was too LOW.");
}
else {
System.out.println ("Your guess was too HIGH.");
guesses++;
}
}
}
System.out.println("Would you like to play again?(Y/N)");
playAgain = scan.next();
}
底部应该如下:
guesses++;
}
}
System.out.println("Would you like to play again?(Y/N)");
playAgain = scan.next();
}
}
它的方式意味着while
的条件永远不会更新。我假设您希望在用户的每次输入后更新它。