首先,感谢您阅读我的帖子并帮助我。
我正在尝试编程,我定义一个随机数,程序猜测这个随机数,然后,根据我说猜测是太高还是太低,程序再次猜测。
当程序猜出一个过高的数字时,用户要输入"较低",然后程序只猜测较低的数字。
理想情况下,程序将考虑所有先前选择的结果。因此,如果猜测 #1 太高,这应该仍然是之后所有迭代的上限。我们不希望每次迭代时只更改上限或下限。
我尝试用我的代码做的是重置用于计算随机数(线程本地随机(的最小值和最大值。
主要问题是我无法重置 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-condition 检查更高和更低。并在做完后关闭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();
我做了一些编辑并添加了一个while循环,检查一下。我测试了它,它似乎正在工作。
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 (!"Correct".equalsIgnoreCase(userReply)){
if ("Higher".equalsIgnoreCase(userReply)) {
oMin = randomNumber;
}
if ("Lower".equalsIgnoreCase(userReply)) {
oMax = randomNumber;
}
randomNumber = ThreadLocalRandom.current().nextInt(oMin, oMax);
System.out.println("Is " + randomNumber + " the right answer?");
userReply = scanner.next();
}
if (userReply.equalsIgnoreCase("Correct")) {
System.out.println("We finally did it! " + correctAnswer + " was the correct answer.");
}
}
}