首先,感谢您阅读我的帖子并为我提供帮助。
我正在尝试编程,在其中定义一个随机数,程序猜测这个随机数,然后根据我说的猜测是否太高或太低,程序再次猜测。
当程序猜测的数字太高时,用户应输入“lower”,然后程序仅猜测较低的数字。
理想情况下,程序会考虑之前所有选择的结果。因此,如果猜测#1 太高,则这应该仍然是之后所有迭代的上限。我们不希望每次迭代时只改变上限或下限。
我尝试对代码执行的操作是重置用于计算随机数( ThreadLocalRandom )的最小值和最大值。
主要问题是我无法重置 oMin 和 oMax 值。我不明白如何解决这个问题,很抱歉,如果这是一个完全愚蠢的问题。
再次感谢!
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class J4AB_S11_C3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int oMin = 0;
int oMax = 101;
int randomNumber = ThreadLocalRandom.current().nextInt(oMin, oMax);
String userReply;
System.out.println("What's the lucky number, kiddo?");
int correctAnswer = scanner.nextInt();
System.out.println("Is " + randomNumber + " the right answer?");
userReply = scanner.next();
while ("Higher".equalsIgnoreCase(userReply)) {
oMin = randomNumber;
}
while ("Lower".equalsIgnoreCase(userReply)) {
oMax = randomNumber;
}
if (userReply.equalsIgnoreCase("Correct")) {
System.out.println("We finally did it! " + correctAnswer + " was the correct answer.");
}
}
}
最佳答案
对此使用 do-while、if 条件来检查较高和较低。并在 do-while 后关闭 scanner
Scanner scanner = new Scanner(System.in);
int oMin = 0;
int oMax = 101;
String userReply;
int correctAnswer;
do {
int randomNumber = ThreadLocalRandom.current().nextInt(oMin, oMax);
System.out.println("What's the lucky number, kiddo?");
correctAnswer = scanner.nextInt();
System.out.println("Is " + randomNumber + " the right answer?");
userReply = scanner.next();
if ("Higher".equalsIgnoreCase(userReply)) {
oMin = randomNumber;
}else if ("Lower".equalsIgnoreCase(userReply)) {
oMax = randomNumber;
}
} while (!userReply.equalsIgnoreCase("Correct"));
System.out.println("We finally did it! " + correctAnswer + " was the correct answer.");
scanner.close();
关于java - 使用用户输入迭代 While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61966975/