gpt4 book ai didi

java - 做猜谜游戏的 while 循环

转载 作者:行者123 更新时间:2023-11-30 07:48:08 25 4
gpt4 key购买 nike

我正在编写一个简单的java猜谜游戏,该游戏应该随机选择1到100之间的一个数字,然后在你选择正确的数字后,它会询问你是否想再玩一次。我知道我应该能够使用 Do while 循环来询问用户是否想再次玩,但每次我尝试都无法使其工作。这是我的功能齐全的程序,没有 do while 循环。如果有人可以帮助我提示用户是否想再次玩,我将非常感激。我对编程还很陌生。如果缩进不是 100% 正确,我也深表歉意。

import java.util.Scanner;
import java.util.Random;
public class GuessingGame
{
public static void main (String [] args)
{


//Variables
Random randomNumber = new Random();
Scanner kbd = new Scanner(System.in);
int computerValue = randomNumber.nextInt(100);
int numberOfTries = 0;
int success = 0;
int guess = 0;


//Logic and While Loop



while (success ==0)
{
System.out.println("please enter an integer betwen 1 and 100 inclusive: ");
guess = kbd.nextInt();
numberOfTries++;

if (guess < 1 || guess > 100){
System.out.println("Invalid input");
}

else if (guess == computerValue){
success++;
System.out.println("Congratulations you won! Your numbers of tries was: " + numberOfTries + " and the number was: " + computerValue);

}
else if (guess < computerValue){
System.out.println("Your guess is too low!");
}
else if (guess > computerValue){
System.out.println("Your guess is too high!");
}
}



}
}

最佳答案

试试这个:

while(true) {
computerValue = randomNumber.nextInt(100);
numberOfTries = 0;
while (true) {
System.out.println("please enter an integer betwen 1 and 100 inclusive: ");
guess = kbd.nextInt();
numberOfTries++;

if (guess < 1 || guess > 100) System.out.println("Invalid input");
else if (guess == computerValue) {
System.out.println("Congratulations you won! Your numbers of tries was: " + numberOfTries + " and the number was: " + computerValue);
// leave the first loop
break;
}
else if (guess < computerValue) System.out.println("Your guess is too low!");
else if (guess > computerValue) System.out.println("Your guess is too high!");
}

System.out.println("Do you want to play again? (1:Yes/2:No)");
// if input is not yes leave second loop
if(kbd.nextInt() != 1) break;
}

关于java - 做猜谜游戏的 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33662244/

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