0

I'm a new programmer and I'm learning multidimensional arrays. I wrote this simple code and I dont know why I get this compile error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at Arrays.main(Arrays.java:21)

 public class Arrays {

    public static void main(String[] args) {

        int [][][] a  = new int [2][3][4];

        for(int i = 0; i < a.length; i++){

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

                for(int k = 0; k < a[j].length; k++){
                System.out.print(a[i][j][k]);
            }
            System.out.println();
        }
        System.out.println();
    }
    System.out.println();
 }
}

If I change the array to be 3x3x3 the code works

public class Arrays {

    public static void main(String[] args) {

        int [][][] a  = new int [3][3][3];

        for(int i = 0; i < a.length; i++){

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

                for(int k = 0; k < a[j].length; k++){
                System.out.print(a[i][j][k]);
            }
            System.out.println();
        }
        System.out.println();
    }
    System.out.println();
 }
}

Why?

  • 3
    `for(int k = 0; k < a[j].length; k++)` should be `for(int k = 0; k < a[i][j].length; k++)`. A comment on your code: you use too many blank lines. You should reduce the number of blank lines. Also, please take more care wrt. your indentation. – Turing85 Jun 12 '18 at 19:32

1 Answers1

-1

Its very simple . Your array does not have equal rows and columns to process such an iteration . You can clear your own doubt . Just print out values of i , j , and k . You will be able to see that at certain point in your iteration there is no such index to be referred . Hence it is a compile time error

Major
  • 53
  • 7