gpt4 book ai didi

java - 无法成功重新循环 while 循环

转载 作者:行者123 更新时间:2023-12-02 03:02:42 26 4
gpt4 key购买 nike

我在以下代码中的目标是不断进行猜测,直到用户猜测正确的数字或​​退出。要退出,我可以轻松地跳出循环,但是当我尝试继续循环时,它无法正常工作。首先它需要多个输入,然后还完全重新生成我的数字,而我想要做的是不断猜测(询问用户)相同的随机数。下面是我的代码:

public class Test {
public static void main(String[] args) {
int count, randNum, guess;
count = 0;
Scanner scan = new Scanner(System.in);

while (true) {
Random rand = new Random();
randNum = rand.nextInt(100) + 1;
System.out.println("Guess a number b/w 1 and 100");
guess = scan.nextInt();
count += 1;

if (guess == randNum) {
System.out.println("Correct guess.");
System.out.println("It took " + count + " tries to guess the right number");
System.out.println("Would you like to play again? ");
System.out.println("Press any letter to play again or q to quit: ");
if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
break;
}
else{
continue;
}
}
if (guess > randNum) {
System.out.println("Your guess is bigger than actual number. Would you like to try again?");
System.out.println("Press q to quit or any other letter to try again");
if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
break;
}
else {
continue;
}
}
else if (guess < randNum) {
System.out.println("Your guess is smaller than actual number. Would you like to try again?");
System.out.println("Press q to quit or any other letter to try again");
if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
break;
}
else {
continue;
}
}

}

}

}

最佳答案

生成随机数的代码应该放在while语句之前。当您调用 continue 时,它会返回到 while block 的第一行,从而生成另一个随机数。

关于java - 无法成功重新循环 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42218262/

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