Input a 2D array using foreach loop

Viewed 881

I want to convert the following traditional for loop to foreach loop:

for(int i=0;i<3;i++)
    for(int j=0;j<3;j++)
        arr[i][j]=sc.nextInt();

My attempt is:

for(int[] innerArr: arr)
    for(int ele: innerArr)
        ele = sc.nextInt();

This doesn't work. I thought that since innerArr represents a row of the array, and ele represents a single element in that row, the above code would work. But I guess only the existing value of that element in arr[i][j] is copied into ele. Is it even possible to assign a value to that element using a foreach loop?

2 Answers

No, it's not possible. An enhanced for loop gives you copies of the array elements (or the elements of the Iterable) you are iterating over, so assigning values to them doesn't change the original array (or Iterable).

Your enhanced for loop attempt is equivalent to:

for(int i = 0; i < arr.length; i++) {
    int[] innerArr = arr[i];
    for(int j = 0; j < innerArr.length; j++) {
        int ele = innerArr[j];
        ele = sc.nextInt();
    }
}

You should stick with the traditional for loop in this case.

The inner loop can't be an enhanced for-loop if you want to write to an element. What you can do is:

for(int[] innerArr : arr) {
  for(int i = 0; i < innerArr.length; i++) {
    innerArr[i] = scanner.nextInt();
  }
}

Have a look at JLS14.14.2. Then you can see what the compiler is doing to an array access.

Related