Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将do while循环中的变量和外部变量声明为随机数_Java_Loops_While Loop - Fatal编程技术网

Java 将do while循环中的变量和外部变量声明为随机数

Java 将do while循环中的变量和外部变量声明为随机数,java,loops,while-loop,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().n

我一直在尝试编写代码,这使机器猜测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);
未定义回答

我正在尝试循环,直到
random
等于
answer

问题是,如何将
answer
变量定义为随机变化的数字,而变量
random
保持不变


提前谢谢

您必须在(…)时在
do{}之外定义
int-answer

公共静态void main(字符串[]args){


这是我做的工作,对我来说是有意义的!谢谢!使用<代码> java。UTIL.RADION/code >随机数生成。<代码> THealLoad随机/<代码>在不同的上下文中使用。你应该考虑使用IDE。IDE会直观地告诉你,你已经犯了这样的错误,在最早的时间(甚至不编译源代码)。
    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);
}