好的,我的代码在这里:http://www.so.pastebin.com/m7V8rQ2n
我想知道...假设我有一个可以在图 block 上重绘的图像...有没有办法检查 future 的图 block ,这样我就不会超出已定义的图 block map 的范围?
就像如果我在 map 的边缘......它不会让我过去?
谢谢。
最佳答案
一般来说,只需确保索引在界限内即可防止 ArrayIndexOutOfBoundsException
。
JLS 10.4 Array Access
All arrays are 0-origin. An array with length
n
can be indexed by the integers0
ton-1
.
因此,像这样的简单检查是非常典型的:
if (i >= 0 && i < arr.length) {
System.out.println(arr[i]);
}
除非像 arr
在检查和访问之间重新分配这样令人讨厌的事情,上面的代码将永远抛出ArrayIndexOutOfBoundsException
。
二维数组“板”
通常,您可以更具体,例如当您将矩形“板”存储在二维数组(或者更确切地说,Java 中的数组的数组)中时。
final int M = 10; // height, i.e. number of rows
final int N = 8; // width, i.e. number of columns
final int[][] board = new int[M][N];
然后你可以使用如下方法:
boolean isInBound(int r, int c) {
return (r >= 0) && (r < M) && (c >= 0) && (c < N);
}
绑定(bind)检查更容易阅读和编写,因为我们知道我们有一个 MxN 板。如果 isInBound(r, c)
,则 board[r][c]
将永远抛出 ArrayIndexOutOfBoundsException
。
关于java applet - 数组检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2955126/