检查二维数组中的边界 [英] Checking for out of bounds in a 2D array
问题描述
我正在尝试检查2D数组中每个元素的相邻值,但是当我到达数组的边或角落时,得到了IndexOutOfBoundsException.例如,如果我的数组是:
I'm trying to check the neighboring values of each element in a 2D array but am getting an IndexOutOfBoundsException when I reach the sides of the array or a corner. For example if my array is:
我知道8的所有邻居都是7,5和6,但是我的if
语句没有正确检查边界.我为此提供的代码是:
I know that all the neighbors of 8 are 7,5 and 6, but my if
statements don't check the bounds properly. The code I have for this is:
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)
我已经研究了一段时间,并经历了许多不同的技术来解决这个问题.任何帮助将是巨大的.谢谢.
I've been working on this for a while and have gone through many different techniques to solve this. Any help would be great. Thanks.
推荐答案
如果您要获取所有相邻单元格并对其进行处理(例如添加它们),则需要进行某种边界检查,例如,对此进行修改的方法可能会起作用:
If you're trying to get all the neighbor cells and do something with them, for example add them, then you need to do some sort of bounds checking, for example something modified from this could work:
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
这篇关于检查二维数组中的边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!