在do-while循环和外部将变量声明为随机数

时间:2017-03-13 23:39:51

标签: java loops while-loop

我一直在尝试编写代码,这使得机器猜测从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保持不变?

提前致谢!

1 个答案:

答案 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);
}