英文:
Get all neighbors of cell in array without out of bounds exception
问题
我试图从数组中邻近给定单元格的所有单元格中创建一个ArrayList。目前,我的代码对于在最后一行或最右列没有邻居的任何单元格都有效。如果它在这些位置有邻居,我会收到错误消息:“Exception in thread“main”java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3”
以下是我的代码:
获取2x2网格中单元格(1,1)的邻居
返回:[0, 0, 0, 0, 0, 0, 1, 1](正确运行)
但如果我查找第2行/列的任何单元格的邻居,我会收到错误,我不知道哪里出错了。
请帮帮我!!
英文:
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 2x2 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!!
答案1
得分: 0
你的边界检查是错误的。
c >= 0 && r >= 0 && r < landscape.length && c < landscape[r].length
英文:
Your bounds check is wrong.
c >= 0 && r >= 0 && r < landscape.length && c < landscape[r].length
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论