Josh Miller
Josh Miller

Reputation: 11

Math.random() and Random::nextInt always give the same exact number inside a for loop

So I am trying to make an Array with random numbers, but whenever I try Math.random or create a new Random object and use it, I always get the same number multiple times. My code is this one:

int[] Array = new int[size];
for (int Y : Array) {
    Array[Y] = (int) (Math.random() * 10) + 3;
}

or this one:

int[] Array = new int[size];
for (int Y: Array) {
    Array[Y] = rand.nextInt(30); 
}

The output im getting is: [0][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3]

I haven't set a seed and I tried it outside the loop and inside but still only get the same number.

Upvotes: 0

Views: 87

Answers (1)

mat
mat

Reputation: 126

You are not referring to the index of the array, but to the specific element which remains the same. You have to use indexed loop.

Try with that (it is a good practice to use camelCase for variables, so 'Array' starting with small 'a')

int[] array = new int[size];
for(int i = 0; i < array.length; i++) {
    array[i] = rand.nextInt(30);
}

Upvotes: 5

Related Questions