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
Loops 随机数的打印循环_Loops_Random_Printing_Numbers - Fatal编程技术网

Loops 随机数的打印循环

Loops 随机数的打印循环,loops,random,printing,numbers,Loops,Random,Printing,Numbers,有人能解释为什么程序1只重复打印一个随机数吗?下面的程序2打印100个随机数?还有,是否需要编辑程序1来完成程序2所做的工作 方案1 public class RandomComparison { public static void main(String[] args){ int rnd = (int) Math.random() * 6 + 1; for(int i=0; i<100; i++){ System.out.p

有人能解释为什么程序1只重复打印一个随机数吗?下面的程序2打印100个随机数?还有,是否需要编辑程序1来完成程序2所做的工作

方案1

public class RandomComparison {

    public static void main(String[] args){

        int rnd = (int) Math.random() * 6 + 1;

        for(int i=0; i<100; i++){
        System.out.print(rnd);
        }

    }


}
公共类随机比较{
公共静态void main(字符串[]args){
int rnd=(int)Math.random()*6+1;

对于(int i=0;i,在第一种方法中,您将检索一个随机值并打印该单个值100次。第二种方法是生成一个随机数100次,并在每次迭代中打印它

int rnd = (int) Math.random() * 6 + 1;//grabbed only once

for(int i=0; i<100; i++){
    System.out.print(rnd);//printing `rnd` 100 times
}



for (int i=0; i<100; i++){
        roll = randomInt(1, 6);//calling for a new random number with each iteration, then printing it
        System.out.print(roll);
}
要修复第一个方法并使其与第二个方法相同运行,请执行以下操作:

public class RandomComparison {

   public static void main(String[] args){

       for(int i=0; i<100; i++){
           System.out.print((int)(Math.random()* 6) + 1);//prints out a random number with every iteration
       }
   }
}
公共类随机比较{
公共静态void main(字符串[]args){

对于(int i=0;i因为您正在打印同一个变量
rnd
谢谢,这很有意义。我是如何让它生成100次rnd的?我试图将初始化语句移动到循环中,但仍然只有1个数字重复了100次。您是在问如何生成100次随机数并打印每个随机数?如果是,则上面代码中的第二个for循环与
randomInt
方法一起实现了这一点。您只需正确使用方法参数。我将把这一点放在我的答案中。您的第一个问题是肯定的。我只是想知道除了创建另一个类之外,是否还有其他方法生成100次随机数。我觉得有一个比必须这样做更简单的方法。你是说创建两个程序来尝试并完成相同的壮举?还是第二种方法-在本例中是
randomInt()
?我现在明白我的错误了。非常感谢!我现在明白了。
public static int randomInt(int low, int high){
    int result = (int) (Math.random()*(high) + low);//replace `6` with the parameter `high`
    return result;
}
public class RandomComparison {

   public static void main(String[] args){

       for(int i=0; i<100; i++){
           System.out.print((int)(Math.random()* 6) + 1);//prints out a random number with every iteration
       }
   }
}