我寫了一段代碼,它一直給我一個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