2015-04-23 46 views
0
// Counts the neighbors of alive or dead cells in boolean grid. 
    public static int countNeighbors (final boolean[][] grid, final int row, final int col) { 
     // Finds neighbors in top row. 
     int count = 0; 
     for (int i = 1; i > -1; --i) { 
      if (grid[row - 1][col + i] == true) 
       count += 1; 
      else if (grid[row - 1][col + i] == false) 
       count += 0; 
     } 

     // Finds neighbors in same row. 
     for (int i = 1; i > -1; --i) { 
      if (grid[row][col + i] == true) 
       count += 1; 
      else if (grid[row][col + i] == false) 
       count += 0; 
     } 

     // Finds neighbors in bottom row. 
     for (int i = 1; i > -1; --i) { 
      if (grid[row + 1][col + i] == true) 
       count += 1; 
      else if (grid[row + 1][col + i] == false) 
       count += 0; 
     } 

     return count; 
    } 

當我試圖在指定的正方形周圍的所有8個塊中查找所有真正的鄰居值時,獲取數組越界。18x18板陣列索引出界

我覺得代碼已經可以處理,如果它超出了界限,因爲我認爲這些值將是錯誤的。

+0

你的問題是什麼?在訪問數組之前,只需檢查行和列是否在範圍內。 – samgak

+0

此代碼充滿了問題。只是第一個'if'語句('if(grid [row - 1] [col + i] == true)')將導致越界異常。 –

+0

Java數組是基於零的。 –

回答

0

創建一個單獨的函數來獲取網格單元,包括邊界檢查:

public static boolean getGridCell (final boolean[][] grid, final int row, final int col) 
{ 
    // bounds check: 
    if((row < 0) || (row >= grid.length)) 
     return false; 
    if((col < 0) || (col >= grid[row].length)) 
     return false; 

    return grid[row][col]; 
} 

然後調用這個函數,而不是直接訪問網格:

public static int countNeighbors (final boolean[][] grid, final int row, final int col) { 
    // Finds neighbors in top row. 
    int count = 0; 
    for (int i = 1; i >= -1; --i) { 
     if (getGridCell(grid, row - 1,col + i)) 
      count += 1; 
    } 

    // Finds neighbors in same row. 
    for (int i = 1; i >= -1; --i) { 
     if (getGridCell(grid, row, col + i)) 
      count += 1; 
    } 

    // Finds neighbors in bottom row. 
    for (int i = 1; i >= -1; --i) { 
     if (getGridCell(grid, row + 1, col + i)) 
      count += 1; 
    } 

    return count; 
} 

另外:

  • 沒有必要檢查網格單元是否爲空,並且如果它是零,則計數,因爲這不會產生任何差異對伯爵的看法。你不需要測試if(some_boolean == true),你可以直接寫if(some_boolean)
  • 你的循環終止條件應該是> = -1 not> -1,如果你打算包括-1 。