ArrayIndexOutOfBoundsException error while executing code

0

My code is giving the following error:

  

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at t151.main (t151.java:19)

What does this mean and how do I fix it?

Follow the code:

       public class t151 {

        static final int n = 10;

            public static void main (String[] args){

                int A[][] = new int [n][n];

                int i,j;

                    for (i=0; i < n; i++){
                        for (j=0; j < n; j++){

    }
                            System.out.print (A[i][j]);     
}
}
}
    
asked by anonymous 03.11.2016 / 23:36

1 answer

3

The System.out.print(A[i][j]); line is outside the second loop, and the output condition of the second loop is j greater than or equal to n (which is worth 10), which causes you to access a nonexistent position of the vector (it has 10 positions but goes from 0 to 9). This is why java accuses ArrayIndexOutOfBoundsException .

To fix, change as below by adding the line mentioned inside the second loop:

public class t151 {

    static final int n = 10;

    public static void main (String[] args){

        int A[][] = new int [n][n];

        int i,j;

        for (i=0; i < n; i++){
            for (j=0; j < n; j++){
                System.out.print (A[i][j]); 
            }    
        }
    }
}
    
03.11.2016 / 23:47