0
public class MDarrays_28 { 
    public static void main(String[] args){
        int flats[][];  
        flats= new int[2][3];
        flats[0][0]=101;
        flats[0][1]=102;
        flats[0][2]=103;
        flats[1][0]=201;
        flats[1][1]=202;
        flats[1][2]=203;
        
        for(int i=0;i<flats.length;i++){   
            for(int j=0; i<flats[i].length;j++){
            System.out.print(flats[i][j]);
            System.out.print(" ");
        }
        System.out.println("\n");
      } 
    }
    
}

the output- 101 102 103 0 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4 at MDarrays_28.main(MDarrays_28.java:15)

im very new to computer programming so any help would be really appreciated, thanks a ton!

vee
  • 21
  • 2
  • 1
    Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Henry Twist May 09 '21 at 21:44

3 Answers3

3

this line is wrong:

for(int j=0; i<flats[i].length;j++){

you should fix it:

for(int j=0; j<flats[i].length;j++){
dev55555
  • 403
  • 1
  • 12
0

I would recommend using a for-each loop in this case: it's more efficient and it doesn't give you headaches with variables.

The following should work:

for(int[] i : flats){
   for(int j : i){
      System.out.print(j+" ");
   }
   System.out.println();
}

Which prints:

101 102 103 
201 202 203 
Spectric
  • 5,761
  • 2
  • 6
  • 27
0

I see the inner for loop, the test condition is incorrect. Since your iterating variable is j(which you are incrementing), your test condition remains constant throughout the execution. Test conditions should be selected in such a way that you evaluate new expressions in every loop.

In your case, the condition should involve variable j, as it is the only variable updated in each loop. So by changing the condition in inner for loop to following it should fix your issue

for(int j=0; j<flats[i].length;j++){
}