user2998504
user2998504

Reputation: 75

Where is the Out Of Bound Multidimensional Array

Getting OBE from MD array. As far as I can see its cumming from the inner loop

    int[][] page = new int[3][3];
    int row = -1;
    int column = 0;
    int count = 0;

    for (int i = 0; i <3; i++)
    {
        row++;
        for (int j = 0; j < 3; j++)
        {
        column++;
        count++;
        page[row][column] = count;
        }
    }

I'm expecting:

FirstLoop
row 0 column 1 == 1
row 0 column 2 == 2
row 0 column 3 == 3

SecondLoop
row 1 column 4 == 4
row 1 column 5 == 5
row 1 column 6 == 6


ThirdLoop
row 2 column 7 = 7
row 2 column 8 = 8
row 2 column 9 = 9

Got:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

Upvotes: 0

Views: 330

Answers (3)

nhgrif
nhgrif

Reputation: 62062

Your inner for loop is incrementing column. You make it through the first run of the outer loop just fine. But on the second iteration of the outer loop, column hasn't been reset, so you're trying to access index 3, which is out of bounds.

EDIT: As is pointed out in a comment, the problem is also because you're starting column at 0, so you'd run out of bounds on the last iteration of the inner loop on the first iteration of the outer loop. But even if column starts at a -1, you'd run out of bounds by the first iteration of the inner loop on the second iteration of the outer loop. Regardless, there is a much less confusing, much more readable way of accomplishing what you're trying to accomplish, as I've demonstrated below.

Reset column = 0 inside the outerloop, outside the innerloop.

The EASIEST fix, by far, is to just do this:

int[][] page = new int[3][3];
int count = 0;

for (int row = 0; row<3; ++row) {
    for (int column = 0; column < 3; ++column) {
        count++;
        page[row][column] = count;
    }
}

Upvotes: 4

Melquiades
Melquiades

Reputation: 8598

You're getting OBE on the second iteration, because you have 3 columns, and column variable in being incremented above 3 on the second iteration. Just add column = 0 in the outer loop. You need also to move incrementing column (you can do it in below page[row][column++] = count), because you're incrementing column before using it in the array, hence it will become 4 on all inner loop iteration, giving you another OBE.

for (int i = 0; i <3; i++)
{
    row++;
    //reset column
    column = 0;
    for (int j = 0; j < 3; j++)
    {
        count++;
        //increment column after it's first use
        page[row][column++] = count;
    }
}

Upvotes: 0

wvdz
wvdz

Reputation: 16651

You forgot to reset the column var.

Upvotes: 0

Related Questions