如何在java中创建和显示随机数的arraylist?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4307273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:41:46  来源:igfitidea点击:

How can I create and display an arraylist of random numbers in java?

javaarraylistrandom

提问by Sparky123

I'm trying to generate an arraylist of random numbers and display it. I'm not sure where I'm going wrong. I think my showArray method isn't working properly because it's displaying two random numbers and then repeating the second one n-2 times.

我正在尝试生成一个随机数数组列表并显示它。我不确定我哪里出错了。我认为我的 showArray 方法不能正常工作,因为它显示两个随机数,然后重复第二个 n-2 次。

private static ArrayList<Integer> RandomArray(int n)
    {

        ArrayList<Integer> arrayRandom = new ArrayList<Integer>(n);

        for (int i=0; i<n; i++)
        {
            Random rand = new Random();
            rand.setSeed(System.currentTimeMillis());
            Integer r = rand.nextInt() % 256;
            arrayRandom.add(r);

        }

        return arrayRandom;

    }

private static void ShowArray(ArrayList<Integer> randomArray)
{
    int n = randomArray.size();

    ArrayList<Integer> showArray = new ArrayList<Integer>(n);

    for (int i = 0; i<n; i++)
    {
        int r = randomArray.get(i);
        showArray.add(r);
    }
    System.out.println(showArray);

}

public static void main(String args[])
    {

        ShowArray(RandomArray(5));

    }

So for example this would produce an output of

因此,例如这将产生输出

[132, 152, 152, 152, 152]

[132, 152, 152, 152, 152]

Any help is much appreciated. Thanks in advance

任何帮助深表感谢。提前致谢

采纳答案by Jan Thom?

Take the random object out of your loop and don't set the seed everytime.

从循环中取出随机对象,不要每次都设置种子。

ArrayList<Integer> arrayRandom = new ArrayList<Integer>(n);

Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
for (int i=0; i<n; i++)
{
    Integer r = rand.nextInt() % 256;
    arrayRandom.add(r);
}

This should work better.

这应该工作得更好。

回答by Tim Bender

You problem is that you keep resetting the seed and thus restarting the pseudo random number generator (PRNG) sequence.

您的问题是您不断重置种子,从而重新启动伪随机数生成器 (PRNG) 序列。

Do this:

做这个:

Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
for (int i=0; i<n; i++)
{
    Integer r = rand.nextInt(256);
    arrayRandom.add(r);

}

回答by Falmarri

Don't set the seed every iteration

不要每次迭代都设置种子

        Random rand = new Random();
        rand.setSeed(System.currentTimeMillis());

Do it once.

做一次。