Search code examples
javaarraysfor-loopforeach

Java's advanced for loop not inputting captured values from nextInt properly


After initializing an array and using the For-Each Loop to capture 2 input values and update in the array, printing the values out results only in the last integer input showing, a zero.


int[] testArray = new int[2];
Scanner input = new Scanner(System.in);

for(int val : testArray) {
    testArray[val] = input.nextInt();
}

for(int x = 0; x < testArray.length; ++x){
    System.out.println(testArray[x]);
}

Using the normal for loop works when capturing input. Not sure what is going on logic-wise with the advanced for loop.


Solution

  • int[] testArray = new int[2];

    This makes a new array, containing the values 0, and 0. Then assigns it to variable testArray.

    for(int val : testArray)

    This loops through the values of the array, NOT the indices.

    In other words, the first time through the loop, val is 0. The second time through the loop, val is.. also 0.

    You are used to:

    for (int i = 0; i < testArray.length; i++) {
      testArray[i] = input.nextInt();
    }
    

    which is different from what you have now - this 'old' for loop style loops through each index, whereas the new one loops through each value.

    If you want to loop indexes, the old loop is what you have to do. The new snippet is only for iterating through values, which you don't have. The for (type name : collectionOrArray) syntax cannot assign new values to the collection or array, only read them. Given that you want to assign, you can't use it.