Sparky123
Sparky123

Reputation: 13

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

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.

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]

Any help is much appreciated. Thanks in advance

Upvotes: 1

Views: 28886

Answers (3)

Falmarri
Falmarri

Reputation: 48559

Don't set the seed every iteration

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

Do it once.

Upvotes: 0

Tim Bender
Tim Bender

Reputation: 20442

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

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);

}

Upvotes: 1

Jan Thom&#228;
Jan Thom&#228;

Reputation: 13604

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.

Upvotes: 6

Related Questions