Generally speaking, an ArrayIndexOutOfBoundsException
is thrown when there's an attempt to access an array element at an index that is out of bounds.
The following snippet shows some scenarios (independent of each other) where ArrayIndexOutOfBoundsException
are thrown:
// 1
int[] x = new int[5];
x[-1] = 0; // ArrayIndexOutOfBoundsException: -1
// 2
int[] x = new int[5];
x[5] = 0; // ArrayIndexOutOfBoundsException: 5
// 3
int[][] table = new int[3][3];
table[0][10] = 0; // ArrayIndexOutOfBoundsException: 10
// 4
int[][] table = new int[3][3];
table[-10][10] = 0; // ArrayIndexOutOfBoundsException: -10
// 5
int[][][][] whoa = new int[0][0][0][0];
whoa[0][-1][-2][-3] = 42; // ArrayIndexOutOfBoundsException: 0
// 6
int[][][][] whoa = new int[1][2][3][4];
whoa[0][1][2][-1] = 42; // ArrayIndexOutOfBoundsException: -1
Where and how this happens in your applet is unclear, but rest assured that it happens for the right reason: you've illegally tried to access an array element at an invalid index, and since arrays are bound-checked at run-time in Java, the run-time exception is raised.
You may want to bring out the debugger to see how the invalid index was evaluated, but if nothing else, lots of System.out.println
wherever you're mutating the index and wherever you're about to access an array element can help locate the bug.
Additional tips:
Instead of:
lastX = lastX + 1;
lastY = lastY - 1;
You can do:
lastX++;
lastY--;
This is called the "post-increment" and "post-decrement" operators. Used judiciously, it can improve readability.