我一直在尝试编写代码,这使得机器猜测从1到1000的随机数。 因为我知道如何用pascal和python编写它,所以我试着在java中编写它,但我现在卡住了。
以下是代码:
import java.util.concurrent.ThreadLocalRandom;
public class Test {
public static void main(String[] args) {
int random = ThreadLocalRandom.current().nextInt(0, 1000);
int count = 0;
do {
int answer = ThreadLocalRandom.current().nextInt(0, 1000);
count++;
} while (random != answer);
System.out.println("Answer: " + answer + " " + "Count: " + count);
}
}
问题是,在这一行
} while (random != answer);
answer
未定义。
我正在尝试循环,直到random
等于answer
。
问题是,如何将answer
变量定义为随机变化的数字,而变量random
保持不变?
提前致谢!
答案 0 :(得分:1)
您必须在int answer
:
do{}while(...)
public static void main(String [] args){
int random = ThreadLocalRandom.current().nextInt(0, 1000);
int count = 0;
int answer;
do {
answer = ThreadLocalRandom.current().nextInt(0, 1000);
count++;
} while (random != answer);
System.out.println("Answer: " + answer + " " + "Count: " + count);
}