我写了一段代码,它一直给我一个ArrayIndexOutOfBoundsException错误,我不知道为什么。我想我已经正确设置了阵列的大小,但显然这是不正确的。即使我将数组的大小设置为100,我仍然得到错误。在代码下方可以找到数据输入。不知道是什么原因导致我的ArrayIndexOutOfBoundsException错误
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
. . . . . . . . . . . . . * .
. . . . . . . . . . . . * . .
. . . . . . . . . . . . * * *
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
* * * * * * * * . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
不要“认为”您已正确设置尺寸:请检查。使用一些战术性的'System.out.println()'语句*验证你的索引是否在有效范围内。 – 2014-09-30 00:34:31
这个Boolean [] [] cellsInput = new Boolean [length - 1] [width - 1];'也是错误的。 – 2014-09-30 00:38:05
查看异常堆栈跟踪以确定发生异常的位置。在该语句之前添加println语句以打印索引值和数组大小。确定哪些值出错。然后通过代码反向工作,找出为什么这个值是错误的。这是基本的调试过程。 – 2014-09-30 00:43:52