0

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.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • According to the usual Java practices, local variables usually start with a lowercase letter, so it would be "array" rather than "Array." Your code will certainly compile either way, but it may make it a bit harder for other Java programmer's to read. – HomeworkHopper Mar 09 '21 at 13:20
  • Related: [How does the Java 'for each' loop work?](https://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work) – Federico klez Culloca Mar 09 '21 at 13:22

1 Answers1

5

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);
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
mat
  • 126
  • 3
  • This worked, thanks a lot! Just one more question, the problem is when i use (int Y:Array) instead of an int i? – Josh Miller Mar 09 '21 at 13:16
  • The problem is due to fact, that when you are iterating over an array and you want to change each element basing on the index, you have to use an iteration index. In that case you use int i = 0 as array start, so for example, the following iterations to 5 refers to indexes: array[0] = rand.nextInt(30); array[1] = rand.nextInt(30); array[2] = rand.nextInt(30); array[3] = rand.nextInt(30); array[4] = rand.nextInt(30); And then you can access each element by its index :) – mat Mar 09 '21 at 13:18
  • 2
    @JoshMiller The problem is that using the `for (int y : array)` form, `y` will not be an index of the array, it will be an element of the array. Since before the loop you instantiated an array without specifying its content, all the elements where set to `int`'s default value (0), so `y` will always be 0 and you were always setting the value of `array[y]`, that is `array[0]` – Federico klez Culloca Mar 09 '21 at 13:19