I just started learning java. Take a look at my code for adding 1 to each element of a 2D Array using enhanced for loop. I have also attached a image of my code in eclipse.Code for Enhanced for loop
package multi_array;
public class MainClass {
public static void main(String args[]){
int array[][]={{1,2,3}, {4,5,6}, {7,8,9}};
add_1(array);
}
public static void add_1(int a[][]){
for(int[] a_row: a){
for(int i: a_row){
a_row[i]+=1;
}
}
for(int[] a_row: a){
for(int i: a_row){
System.out.print(a_row[i]+"\t");
}
System.out.println("\n");
}
}
}
Now when I try to run the program I get below shown error message. I have also attached the image of error message.Error message
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at multi_array.MainClass.add_1(MainClass.java:12)
at multi_array.MainClass.main(MainClass.java:6)
How can I correct this code ?
OK friends first of all sorry for my bad indention of code, after all this is my first question on stackoverflow. I got the correct result by replacing
for(int i: a_row){
a_row[i]+=1;
}
with the code
for(int i=0; i<a_row.length; i++){
a_row[i]+=1;
}
But I just wanted to know if I can get the desired result by using foreach loop only.