1

I'm attempting to write a simple for loop that generates three integers and assigns each value to an array index. The second for loop in my code returns unexpected results. Can someone explain to me what's going on?

import java.util.Random;

public class Main {

public static void main(String[] args) {

    //variables
    int[] array = new int[3];
    Random rand = new Random();

    //all else

    for(int item : array) {                     
            array[item] = rand.nextInt(100)+1;
            System.out.println(array[item]);                                
    }       

    System.out.println("\n " +  array[0] + " " + array[1] + " " + array[2]);

    for(int i = array.length; i > 0; i--){
        System.out.println(array[i-1]);         
    }       

}

}
JaneDough
  • 13
  • 2
  • Why do you think `item` holds semantically correct array indices? – Tom Dec 29 '17 at 05:36
  • `int[] array = new int[3];` creates integer array with default value 0 at each index. You are looping over array values which is 0 all the time, when you are populating array, it will be array[0] always, so array[0] will have the last random number, since values at other index are untouched, they are 0. – kratostoical Dec 29 '17 at 05:42

1 Answers1

2
for (int item : array) {                     
    array[item] = rand.nextInt(100)+1;
    System.out.println(array[item]);                                
}

By using an enhanced for-loop, the value of item will always be 0, as the array was just initialized before the start of the loop. Essentially, this will just set the first index of the array to a random value (between the range you defined) and print it.

To correctly iterate over the array, you should use the following:

for (int i = 0; i < array.length; i++) {                     
    array[i] = rand.nextInt(100)+1;
    System.out.println(array[i]);                                
}
Jacob G.
  • 28,856
  • 5
  • 62
  • 116