javaarraysmultidimensional-array

Where is the Out Of Bound Multidimensional Array


Getting OBE from MD array. As far as I can see its coming 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


Solution

  • 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;
        }
    }