2014-09-30 199 views
0

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

不要「認爲」您已正確設置尺寸:請檢查。使用一些戰術性的'System.out.println()'語句*驗證你的索引是否在有效範圍內。 – 2014-09-30 00:34:31

+0

這個Boolean [] [] cellsInput = new Boolean [length - 1] [width - 1];'也是錯誤的。 – 2014-09-30 00:38:05

+0

查看異常堆棧跟蹤以確定發生異常的位置。在該語句之前添加println語句以打印索引值和數組大小。確定哪些值出錯。然後通過代碼反向工作,找出爲什麼這個值是錯誤的。這是基本的調試過程。 – 2014-09-30 00:43:52

回答

2

的問題是在這裏:

if (count <= length) { 

最終,這會嘗試引用

cellsInput[y++][length] 

其中長度是第二個數組的長度。但是,第二個數組中的最後一個索引實際上是length - 1

這裏出現的問題是因爲Java中的所有數組都以0開頭。所以你總是想做

if (count < length) { 

只要長度是長度就是數組的長度。

長度始終是數組中的對象數,它從1開始計數。

實施例:

Array arr1 = [a, b, c, d] 
Length of arr1 = 4, it has 4 elements 

Element | Index 
-------------------- 
    a  | 0 
    b  | 1 
    c  | 2 
    d  | 3 

正如你可以看到索引圖4是出界。因此,當您嘗試引用arr1[arr1.length]時,您將得到一個IndexOutOfBoundsException

4

例如下面一行是錯誤的:

if (count <= length) { 

由於您使用數作爲指標,當計數等於長度超過最大索引length - 1 - 因此ArrayIndexOutOfBoundsException。它應該是:

if (count < length) { 
相關問題