Java 检查二维数组中的越界
我试图检查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,但是我的Java 检查二维数组中的越界,java,arrays,Java,Arrays,我试图检查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
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)
int numorrows=imageArray.length;
int numOfColumns=imageArray[0]。长度;
for(int i=0;i0)
如果((i-1)>0)
如果((i+1)=0&(j-1)>=0)
如果((i+1)=0)
如果((i-1)>=0&(j+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
}
}
}
}
}
for(int i=0;i 对于(int innerI=iMin;innerI如果您试图获取所有相邻单元格并对其执行某些操作,例如添加它们,则需要执行某种边界检查,例如,根据此操作修改的某些操作可能会起作用:
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
}
}
}
}
}
for(int i=0;iif((j+1)
将超过边界if((j+1)
将超过边界