java随机数生成器

时间:2013-04-09 12:46:39

标签: java

我不明白什么卷< 1000呢。我的意思是我不明白为什么在rand函数生成随机数时使用它。

public class Hello {
    public static void main(String[] args) {
        Random rand = new Random();
        int freq[] = new int[7];
        for (int roll = 1; roll < 1000; roll++) { // is there a reason for roll<1000
            ++freq[1 + rand.nextInt(6)];
        }
        System.out.println("Face \tFrequency");
        for (int face = 1; face < freq.length; face++) {
            System.out.println(face + "\t" + freq[face]);
        }
    }
}

3 个答案:

答案 0 :(得分:2)

for (int roll =1; roll<1000;roll++){ // is there  a reason  for roll<1000
    ++freq[1+rand.nextInt(6)];
}

这里是什么在freq数组上的随机位置添加+1 999次。

这里的“真实”randome是     rand.nextInt(6) 它会生成0到6之间的数字。

下面:

for( int face=1;face<freq.length;face++){
    System.out.println(face + "\t"+freq[face]);
}

打印freq数组上的6个数字

干净简单的代码:

`public class Hello {
    public static void main(String[] args) {

        //Creates an instance of Random and allocates 
        //the faces of the dices on memory
        Random rand = new Random();
        int freq[] = new int[6];

        //Rolls the dice 1000 times to make a histogram
        for (int roll = 0; roll < 1000; roll++) {
            ++freq[rand.nextInt(6)];
        }

        //Prints the frequency that any face is shown
        System.out.println("Face \tFrequency");
        for (int face = 0; face < freq.length; face++) {
            System.out.println(face + "\t" + freq[face]);
        }
    }
}`

现在它有6个int作为骰子面对内存分配,滚动1000次并且很容易理解,因为它应该是

答案 1 :(得分:0)

因为他们只想生成多达999个随机数。

答案 2 :(得分:0)

在这种情况下,滚动用作for循环中的计数器,一旦达到限制就打破循环。在此示例中,限制为1000。由于roll初始化为1,因此会生成999个数字。