I’m trying to make an ArrayList out of all the cells that neighbor a given cell in an array. Currently, my code works for any cell that does not have neighbors in the last row or right-most column. If it does have neighbors in these, I get the error message: "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3"
Here’s my code:
public ArrayList<Cell> getNeighbors(int row, int col) {
ArrayList<Cell> neighbors = new ArrayList<Cell>();
for (int r = row - 1; r <= row + 1; r++) {
for (int c = col - 1; c <= col + 1; c++) {
if (!(r == row && c == col)) {
if ((c >= 0 && r >= 0) && (c <= (col + 1) && r <= (row + 1))) {
neighbors.add(landscape[r][c]);
}
}
}
}
return neighbors;
}
Getting the neighbors of cell (1, 1) in a 2×2 grid like this one
0 0 0
0 0 0
0 1 1
returns: [0, 0, 0, 0, 0, 0, 1, 1] (Works correctly)
but if I look for the neighbors of any cell in row/col 2, I get the error and I don’t know what I’m doing wrong.
Please help!!
>Solution :
Your bounds check is wrong.
c >= 0 && r >= 0 && r < landscape.length && c < landscape[r].length