Home > database >  ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 for arrays.main
ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 for arrays.main

Time:09-27

import java.util.Scanner;

public class arrays {
    public static void main(String[] args) {
        int i;
        int [][] m1 = new int[2][3];
        int j;

        Scanner sc = new Scanner(System.in);
        
        System.out.println(m1.length);
        System.out.println(m1[0].length);

        for(i = 0; i < m1.length; i  ){
            for(j = 0; i < m1[0].length; j  ) {
                m1[i][j] = sc.nextInt();
            }
        }
        sc.close();
    }
}

I am unable to understand why this error is happening. m1.length and m1[0].length prints correct length of rows and columns. I gave the following input:

1
2
3
4

and then error occured

CodePudding user response:

You have a typo in the inner loop, you go out of bounds of the first axis second axis, because i < m[0].length is true.

Should be as followed ?

  for(j = 0; j < m1[i].length; j  ) {

CodePudding user response:

Finally I solved it, look the second for loop, you put a i instead of j (in the condition). If you use more significant variable names (such as line and column) it's easier to find this type of mistakes

 for(j = 0; j < m1[i].length; j  )
  • Related