有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java检查2D数组中的越界

我试图检查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)

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


共 (1) 个答案

  1. # 1 楼答案

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

    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
                    }
                }
            }
        }
    }
    

    警告:代码尚未编译或测试,主要是向您展示可以做什么,而不是复制粘贴解决方案