Search code examples
javaarraysmultidimensional-arrayindexoutofboundsexception

Why do I get java.lang.ArrayIndexOutOfBoundsException here?


public long process(long[][] theArray) {

    long result = 0l;
    int xDimension = 0;
    int yDimension = 0;

    for (int i = 0; i < theArray.length; i++) {
        for (int j = 0; j < theArray[0].length; j++) {
            if (((yDimension + 12) < theArray.length) && ((xDimension + 12) < theArray[0].length)) {
                result = (theArray[yDimension][xDimension + 1]) + (theArray[yDimension][xDimension + 2])
                        + (theArray[yDimension + 1][xDimension]) + (theArray[yDimension + 1][xDimension + 3])
                        + (theArray[yDimension + 2][xDimension]) + (theArray[yDimension + 2][xDimension + 3])
                        + (theArray[yDimension + 3][xDimension + 1]) + (theArray[yDimension + 3][xDimension + 2]);
            }
            xDimension++;
        }
        xDimension -= (theArray[0].length);
        yDimension++;
    }

    return result;

}// method()

--> my console says : Index 5 out of bounds for length 5. But how is that possible together with my if-condition?


Solution

  • xDimension starts with 0 and will be negative after one iteration of the outer loop.