gpt4 book ai didi

java - 再次玩猜数字游戏

转载 作者:太空宇宙 更新时间:2023-11-04 11:37:54 25 4
gpt4 key购买 nike

我在再次玩游戏时遇到问题。我有一个 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;
}
}

关于java - 再次玩猜数字游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43080345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com