简体   繁体   中英

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 5

I need help with a little array assignment that I am currently doing. So far I managed to correct alof of code but this one problem still remains..

public class AssignmentArray1 {
    public static void main(String[] args) {

        int a[][] = new int[ 10 ][ 5 ];

        for ( int i = 0; i < a.length; i++ )
        {
            for ( int j = 0; j < a[ i ].length; j++ ) {
                a[ j ][ i ] = j;
            }
        }
        for ( int i = 0; i < a.length; i++ )
        {
            for ( int j = 0; j < a[ i ].length; j++ )
                System.out.printf( "%d ", a[ j ][ i ] );
            System.out.println();
        }
    }

}

What's wrong with this? I can't understand why I'm getting the error message

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at assignmentarray1.AssignmentArray1.main(AssignmentArray1.java:25)

So obviously something is wrong with a[ j ][ i ] = j; ? But exactly what is?

It seems you have your indexes swapped by accident for the a array.

This:

            a[ j ][ i ] = j;

Should be:

            a[ i ][ j ] = j;

And this:

            System.out.printf( "%d ", a[ j ][ i ] );

Should be:

            System.out.printf( "%d ", a[ i ][ j ] );

The ending conditions in your two loops are the wrong way round. The easiest way to fix this is to change the assignment as follows:

            a[ i ][ j ] = i;

You also need to fix the second pair of nested loops.

Change from,

a[ j ][ i ] = j;

To,

a[ i ][ j ] = j;

a.length = 10 and a[i].length=5 as per array declaration.

Now, in this for loop

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

as per array boundary 0<=i<10 and 0<=j<5 should be satisfied, but this a[ j ][ i ] = j; statement violates the boundary condition of the array because i can go upto 9 but allowed only in the range [0,5) so ArrayIndexOutOfBoundException is obvious.

Check your for loops and fix the indexing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM