java applet - array checking
Question
OK so my code is here: http://www.so.pastebin.com/m7V8rQ2n
What I want to know... let's say I have an image which I can redraw on tiles... is there a way to check for future tiles so I DON'T go out of bounds of my already defined tile map?
Like if I were at the edge of a map... it would NOT let me go past it?
Thanks.
Solution
Generally speaking, preventing ArrayIndexOutOfBoundsException
can be done by simply making sure that the index is within the bound.
JLS 10.4 Array Access
All arrays are 0-origin. An array with length
n
can be indexed by the integers0
ton-1
.
Thus, a simple check like this is quite typical:
if (i >= 0 && i < arr.length) {
System.out.println(arr[i]);
}
Barring nasty things like arr
getting reassigned between the check and the access, the above code will NEVER throw ArrayIndexOutOfBoundsException
.
2D array "boards"
Often, you can be a lot more specific, e.g. when you have rectangular "boards" stored in a two-dimensional array (or rather, array of arrays in 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];
Then you can have a method like the following:
boolean isInBound(int r, int c) {
return (r >= 0) && (r < M) && (c >= 0) && (c < N);
}
The bound check is both easier to read and to write, since we know that we have an MxN board. If isInBound(r, c)
, then board[r][c]
will NEVER throw ArrayIndexOutOfBoundsException
.