Reputation: 343
I have written a piece of code which keeps giving me an ArrayIndexOutOfBoundsException error and I don't really know why. I think I've set the sizes of the arrays correctly but apparently that isn't true. Even if I set the sizes of the arrays to 100 I still get the error. Below the code you can find the data input.
import java.util.Scanner;
public class GameOfLife {
public static void main(String []args) {
Scanner scanner = new Scanner(System.in);
int length = scanner.nextInt();
int width = scanner.nextInt();
int generations = scanner.nextInt();
Boolean[][] cellsInput = new Boolean[length - 1][width - 1];
System.out.println();
int count = 0;
int y = 0;
while (scanner.hasNext()) {
count++;
if (count <= length) {
if (scanner.next().equals(".")){
cellsInput[y++][count] = false;
} else if (scanner.next().equals("*")) {
cellsInput[y++][count] = true;
}
}
else {
count = 0;
y++;
if (scanner.next().equals(".")){
cellsInput[y++][count] = false;
} else if (scanner.next().equals("*")) {
cellsInput[y++][count] = true;
}
}
}
}
}
Input (for example):
15 15 3
. . . . . . . . . . . . . * .
. . . . . . . . . . . . * . .
. . . . . . . . . . . . * * *
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
* * * * * * * * . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
Upvotes: 0
Views: 57
Reputation: 2534
The problem is here:
if (count <= length) {
Eventually, this is going to try to reference
cellsInput[y++][length]
Where length is the length of that second array. However, the last index in the second array is actually at length - 1
.
The problem here occurs because all arrays in Java start with 0
. So you always want to do
if (count < length) {
whenever length is the length is the length of the array.
Length is always the number of objects in the array, which starts counting at 1
.
Example:
Array arr1 = [a, b, c, d]
Length of arr1 = 4, it has 4 elements
Element | Index
--------------------
a | 0
b | 1
c | 2
d | 3
As you can see index 4 is out of bounds. So when you try to reference arr1[arr1.length]
you get an IndexOutOfBoundsException
Upvotes: 2
Reputation: 7870
For example the following line is wrong:
if (count <= length) {
Since you use count as index, when count equals length, it exceeds the largest index length - 1
- thus ArrayIndexOutOfBoundsException
. It should be:
if (count < length) {
Upvotes: 4