我编写了一段代码,它不断给我一个 ArrayIndexOutOfBoundsException 错误,但我真的不知道为什么。我认为我已经正确设置了数组的大小,但显然这不是真的。即使我将数组的大小设置为 100,我仍然会收到错误。在代码下方您可以找到数据输入。
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;
}
}
}
}
}
输入(例如):
15 15 3
. . . . . . . . . . . . . * .
. . . . . . . . . . . . * . .
. . . . . . . . . . . . * * *
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
* * * * * * * * . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
最佳答案
例如以下行是错误的:
if (count <= length) {
由于您使用 count 作为索引,因此当 count 等于 length 时,它会超过最大索引 length - 1
- 因此出现 ArrayIndexOutOfBoundsException
。应该是:
if (count < length) {
关于java - 不知道是什么导致了我的 ArrayIndexOutOfBoundsException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26110933/