0

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?

1
  • 1
    Replace a[ j ][ i ] by a[ i ][ j ] (in both loops) Commented Dec 1, 2013 at 17:29

4 Answers 4

2

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 ] );
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

Change from,

a[ j ][ i ] = j;

To,

a[ i ][ j ] = j;

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.