Somenath Sinha Somenath Sinha - 1 year ago 109
Java Question

Input a 2D array using for each loop

The equivalent code of what I want using a traditional

for
loop is:

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


My existing code is :

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


This doesn't work. I thought since the 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
. So, is it even possible to assign a value to that element using a for each loop?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download