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,但我的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)
我已经为此工作了一段时间,并通过了许多不同的技术来解决这个问题。任何帮助都会很棒。谢谢。
解决方案
如果您尝试获取所有相邻单元格并对它们执行某些操作,例如添加它们,那么您需要进行某种边界检查,例如从中修改的某些内容可能会起作用:
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
推荐阅读
- json - 如何在弹性搜索中存储星型数据库
- oracle-apex - 如何修复 Oracle Apex 18.2 中的 Textarea 字段帮助文本(?)位置?
- c# - 在 Visual Studio 2017 安装项目中将 .NET Core 添加到先决条件
- charts - 付费图表未显示在 PDF 中
- java - 自定义属性文件在较低的项目层中读取为实体
- python - 传递值的形状不匹配
- html - 如何使用 VBA Excel 引用自动格式化回复电子邮件中的范围?
- laravel - 有没有办法使用查询构建器简单地对多个表进行选择?
- javascript - React Native Elements Button 不会更改禁用状态
- android - 如何创建类似于消息堆栈的whatsapp(首先是聊天屏幕)