Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.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:使用for循环生成一个随机的3位数_Java - Fatal编程技术网

Java:使用for循环生成一个随机的3位数

Java:使用for循环生成一个随机的3位数,java,Java,我需要生成一个随机的3位数使用for循环为一个项目,但我完全卡住了。这是我的 for(int counter = 0; counter < 3; counter++){ randNum = r.nextInt(9 - 9 + 1) + 9; System.out.println(singleNum1); } for(int计数器=0;计数器

我需要生成一个随机的3位数使用for循环为一个项目,但我完全卡住了。这是我的

    for(int counter = 0; counter < 3; counter++){
        randNum = r.nextInt(9 - 9 + 1) + 9;
        System.out.println(singleNum1);
    }
for(int计数器=0;计数器<3;计数器++){
randNum=r.nextInt(9-9+1)+9;
系统输出打印项数(singleNum1);
}

我知道如何通常使用for循环,只是不用于生成数字。每个数字必须分开,然后拼凑在一起。我该怎么做呢?

您可以用不同的方式来做,但这里的主要信息是在开始编码之前检查您正在使用的方法及其工作方式

如果方法的使用很复杂,请使用简单的算法,然后尝试优化它们

以下是一种方法:

    Random r = new Random();
    String output = "";
    for (int i = 0 ; i < 3 ; i++){
        output+=r.nextInt(10);
    }
    int outputInt = Integer.parseInt(output);
Random r=new Random();
字符串输出=”;
对于(int i=0;i<3;i++){
输出+=r.nextInt(10);
}
int outputInt=Integer.parseInt(输出);
这是第二个:

    Random r = new Random();
    int output = 0;
    for (int i = 0 ; i < 3 ; i++){
        output+=(r.nextInt(10)*Math.pow(10, i));
    }
    System.out.println(output);
Random r=new Random();
int输出=0;
对于(int i=0;i<3;i++){
输出+=(r.nextInt(10)*数学功率(10,i));
}
系统输出打印项次(输出);

定义“完全卡住”。您如何获得随机数字,即0-9范围内的整数,记住这包括0,不包括
n
?提示:r.nextInt(9-9+1)与r.nextInt(1)相同,它将始终返回0。成功了!谢谢我不知道每次循环通过时如何获得一个新的数字。现在我知道了“变量”+=再次感谢。