首页 > 解决方案 > 检查二维数组是否越界

问题描述

我正在尝试检查 2D 数组中每个元素的相邻值,但是当我到达数组的两侧或角落时,我得到了 IndexOutOfBoundsException。例如,如果我的数组是:

|2|4|2|7|8|

|8|1|0|5|6|

|0|3|1|5|2|

|1|9|7|2|0|

我知道 8 的所有邻居都是 7,5 和 6,但我的if陈述没有正确检查边界。我为此提供的代码是:

 int numOfRows = imageArray.length;
 int numOfColumns = imageArray[0].length;

 for(int i = 0; i < numOfRows; i++)
    for(int j = 0; j < numOfColumns; j++)

       if((j+1) < numOfColumns-1)

       if((i+1) < numOfRows-1)

       if((j-1) > 0 )

       if((i-1) > 0 )

       if((i+1) < numOfColumns-1 && (j+1) < numOfRows-1)

       if((i-1) >= 0 && (j-1) >= 0)

       if((i+1) < numOfColumns-1 && (j-1) >= 0)

       if((i-1) >= 0 && (j+1) < numOfRows-1)

我已经为此工作了一段时间,并通过了许多不同的技术来解决这个问题。任何帮助都会很棒。谢谢。

标签: javaarrays

解决方案


如果您尝试获取所有相邻单元格并对它们执行某些操作,例如添加它们,那么您需要进行某种边界检查,例如从中修改的某些内容可能会起作用:

for (int i = 0; i < numOfRows; i++) {
    for (int j = 0; j < numOfCols; j++) {
        // check all bounds out of range:
        int iMin = Math.max(0, i - 1);
        int iMax = Math.min(numOfRows - 1, i + 1);
        int jMin = Math.max(0, j - 1);
        int jMax = Math.min(numOfCols - 1, j + 1);

        // loop through the above numbers safely
        for (int innerI = iMin; innerI <= iMax; innerI++) {
            for (int innerJ = jMin; innerJ <= jMax; innerJ++) {
                if (i != innerI && j != innerJ) {
                    // do what needs to be done
                }
            }
        }
    }
}

Caveat: code has not been compiled nor tested and is mainly to show you the idea of what can be done rather than a copy-paste solution


推荐阅读