【发布时间】:2017-03-24 16:02:51
【问题描述】:
所以我在 java 中构建了一种“生命游戏”应用程序,并且在检测索引何时超出范围时遇到了一些问题。下面的代码是来自 SO 的另一个 qustion 的修改版本。
二维数组:
1,1,1,1
1,1,1,1
1,1,1,1
1,1,1,1
代码
private void traverse() {
for (int i = 0; i < brickArray.length; i++) {
for (int j = 0; j < brickArray[i].length; j++) {
System.out.println(i - 1 + "," + j);
checkIfAllowed(i - 1, j);
}
}
}
public void checkIfAllowed(int row, int column) {
boolean incorrect = check(row) && check(column);
if (incorrect) {
System.out.println("Wall");
} else {
System.out.println("Road");
}
}
private boolean check(int index) {
return (index < 0 || index > board.getHeight());
}
结果:
遍历:
-1,0
Road
-1,1
Road
-1,2
Road
-1,3
Road
0,0
Road
0,1
Road
0,2
Road
0,3
Road
1,0
Road
1,1
Road
1,2
Road
1,3
Road
2,0
Road
2,1
Road
2,2
Road
2,3
Road
在本例中,顶部的 4 个单元格应该打印了“Wall”,但他们没有。
【问题讨论】:
-
check在这种情况下似乎暗示 incorrect 而不是 correct -
return (index < 1 || index > board.getHeight());你意识到0小于1,对吧? -
你在哪里定义
board及其方法getHeight()? -
如果索引超出范围,您的检查方法将返回 true。因此,对于 case check(0) && check(0),它将返回 true 对于任何其他情况,它将返回 false,因为只有 true && true == true。假&&真==假,假&&假=假
-
将返回值从
check( )更改为:return index < 0 || index >= board.getHeight( );
标签: java multidimensional-array indexoutofboundsexception traversal