我在再次玩游戏时遇到问题。我有一个 boolean 变量,但是当我输入 yes 或 no 时,程序就会结束。我无法重新启动//Game 循环。我的 boolean 值目前不执行任何操作
//Game
System.out.println("Pick a number between 1-100");
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
int number = rand.nextInt(100)+1;
int round = 0;
int count = 0;
int guess = 0;
int win = 0;
while(win == 0)
{
round++;
System.out.println("Round " + round);
System.out.print("What is your first guess? ");
guess = keyboard.nextInt();
count++;
if (guess == number)
{
if (count == 1)
{
System.out.println("You win in " + count + " guess.");
++win;
break;
}
}
else if (guess > number)
{
System.out.println("That's too high. Try again: ");
}
else if (guess < number)
{
System.out.println("That's too low. Try again: ");
}
}
//Ask to play again
boolean isValidAnswer;
do
{
System.out.print("Would you like to play again (yes/no)? ");
String playAgain = keyboard.next().toUpperCase();
isValidAnswer= playAgain.equals("YES") || playAgain.equals("NO");
if(! isValidAnswer)
{
System.out.println("Error: Please enter yes or no");
System.out.println();
}
}while(!isValidAnswer);
}
}
您在用户赢得猜测之前增加了 round
,这是不正确的,因此将其放置在 if
block 中,这意味着只有当猜测正确时才会递增,如下所示,同时在游戏开始时将 round
初始化为 1。
int round = 1;
int count = 0;
int guess = 0;
int win = 0;
boolean showRound=true;
while(win == 0) {
if(showRound) {
System.out.println("Round " + round);
}
System.out.print("What is your first guess? ");
guess = Integer.parseInt(keyboard.nextLine());//Use scanner.nextLine()
count++;
if (guess == number) {
showRound = true;
round++;//Increment the round only after win
System.out.println("You win in " + count + " guess.");
++win;
break;
} else if (guess > number) {
System.out.println("That's too high. Try again: ");
showRound=false;
} else if (guess < number) {
System.out.println("That's too low. Try again: ");
showRound=false;
}
}
我是一名优秀的程序员,十分优秀!