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板陣列索引出界
我覺得代碼已經可以處理,如果它超出了界限,因爲我認爲這些值將是錯誤的。
你的問題是什麼?在訪問數組之前,只需檢查行和列是否在範圍內。 – samgak
此代碼充滿了問題。只是第一個'if'語句('if(grid [row - 1] [col + i] == true)')將導致越界異常。 –
Java數組是基於零的。 –