获取数组中单元格的所有相邻单元格,不引发越界异常。

huangapple go评论68阅读模式
英文:

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 &gt;= 0 &amp;&amp; r &gt;= 0 &amp;&amp; r &lt; landscape.length &amp;&amp; c &lt; landscape[r].length

huangapple
  • 本文由 发表于 2023年2月19日 11:27:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497797.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定