我目前在大小为4,2的2D数组中使用嵌套for循环。 当我运行我的程序时,我会在下一行中获得索引超出范围的异常
else if (state[i][j+1] != null
&& state[i][j].getFlash() <= state[i][j].getCycleLength()
&& state[i][j+1].getCycleLength() == state[i][j].getCycleLength()){
}
它说索引越界是2.如果我没有检查是否[i] [j + 1]不是null,我会理解错误,但是我不明白该异常校验?我尝试移动!null检查,但程序仍然在此行上失败。
非常感谢任何帮助。
Stack trace:
Exception in thread "Timer-0" java.lang.ArrayIndexOutOfBoundsException: 2
at NatComp.data$1.run(data.java:67)
at java.util.TimerThread.mainLoop(Timer.java:512)
at java.util.TimerThread.run(Timer.java:462)
答案 0 :(得分:3)
只需检查state[i][j+1] != null
即可阻止NullPointerException
,但这并不会阻止代码引发IndexOutOfBoundsException
。
要检查IndexOutOfBounds
,您需要检查indices
与最大允许索引。依赖于使用null检查元素没有意义。如果索引超出范围,您甚至无法访问元素,因此null
检查甚至可能不是checked
。
此外,如果您的if
中有这么多条件,最好在nested
中将它们分开,如果if
检查IndexOutOfBounds
,则为if
new int[3]
进行实际状况检查。那会更具可读性。
例如如果你有一个声明为if (index < 3) {
// you can now access `array[index]`, as it is safe now
// Also, you can add a check for `NPE` here.
}
的数组,那么在访问索引之前,你可以添加一个检查: -
max - 1
那是因为你的指数是从0开始的。因此,最大可访问索引为max
,其中array of array
是数组的大小。
您可以在{{1}}中调整相同的逻辑。
答案 1 :(得分:2)
从您的描述中可以清楚地看到j==1
当您收到异常时。发生这种情况时,state[i][j+1]
会抛出ArrayIndexOutOfBoundsException
,而不是按照您的预期评估为null
。
j
的代码不会引发ArrayIndexOutOfBoundsException
的唯一值为零,因此您可能需要检查该值而不是检查null
。