Dante Dante - 1 month ago 13
Java Question

array index out of boundary exception floodfill java

I am trying to count number of zero from a 2d array by using

floodfill
, but I am getting an
ArrayIndexOutOfBoundsException
. Here is what I've done so far. I commented where the error is.

public class floodfill {

public static int[][] input = new int[][]{
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
};

public static int count = 0;

public static void main(String[] args) {
int row = input.length;
int col = input[0].length;
System.out.println("" + row);
System.out.println("" + col);

apply(row, col);

}

private static void apply(int x, int y) {
int currentColor = getValueAt(x, y);
if (currentColor == 0) {
count++;
apply(x + 1, y);
apply(x - 1, y);
apply(x, y + 1);
apply(x, y - 1);
}
}

private static int getValueAt(int x, int y) {
if (x < 0 || y < 0 || x > input.length || y > input[x].length) {
return -1;
} else {
return input[x][y];
}
}

}

Answer

Your problem here is that when going to getValueAt, you are passing the array length, and array indices stop at .length - 1. The parameter was 1 too much... It wouldn't have thrown an error if your 'if' statement was correct:

// Add equal sign to last 2 conditions
if (x < 0 || y < 0 || x >= input.length || y >= input[x].length) {
    return -1;
}

Other minor stuff:

  • Always capitalize your class names, i.e Floodfill or FloodFill;
  • It's kind of useless to have an 'else' statement after an 'if' statement that returns.
Comments