Arrayindexoutofboundsexception error while executing code

Asked

Viewed 211 times

0

My code is giving the following error:

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

What it means and how to fix?

Follows 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]);     
}
}
}

1 answer

3


The line System.out.print(A[i][j]); is out of the second loop, and the exit condition of the second loop is j be greater than or equal to n(which is worth 10), which causes you to access a non-existent position of the vector (has 10 positions, but goes from 0 to 9). That’s why java accuses the ArrayIndexOutOfBoundsException.

To correct, change as below by adding the mentioned line within 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]); 
            }    
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.