我真的不知道是什麼導致了這個問題,但我的程序應該是康威的生命遊戲,在2代後崩潰,看起來不管我做什麼,而且我我一直在努力尋找錯誤。2D數組和空指針異常(Java)
我把事業縮小到了一些可能的領域 - 或者至少我認爲我有。
short numNeighbors(int x, int y) {
short numNeighbors;
numNeighbors = 0;
if(x > 0 && y > 0 && matrix[x][y] != null){
if (matrix[x+1][y] == true) numNeighbors++;
if (matrix[x][y+1] == true) numNeighbors++;
if (matrix[x+1][y+1] == true) numNeighbors++;
if (matrix[x][y-1] == true) numNeighbors++;
if (matrix[x-1][y] == true) numNeighbors++;
if (matrix[x+1][y-1] == true) numNeighbors++;
if (matrix[x-1][y+1] == true) numNeighbors++;
if (matrix[x-1][y-1] == true) numNeighbors++;
}
return numNeighbors;
}
//returns the number of neighbours that a coordinate has
我假定這部分我上面的二維數組的邊界以外的檢查,但不應該是可能的,因爲我花了預防措施,以確保沒有發生。即便如此,這是一個可能的原因。
void nextGen(){
Boolean[][] newMatrix = new Boolean[rows()][cols()];
for (int i = 1; i < cols()-1; i++){
for (int j = 1; j < rows()-1; j++){
//avoiding null pointer errors
if (matrix[j][i] == null) matrix[j][i] = false;
//if a cell has 3 neighbours, become or stay true
if (numNeighbors(j, i) == 3) newMatrix[j][i] = true;
//if it doesn't have 3 neighbours, become or stay false
else newMatrix[j][i] = false;
}
}
matrix = newMatrix;
}
//makes matrix represent the next generation
這是我對錯誤原因的下一次猜測,但我無法真正知道會出現什麼錯誤。
for (int j = 0; j < numGenerations; j++){
JOptionPane.showMessageDialog(null,"generation " + (j+1) + ":\n\n" + myGrid.showGrid());
myGrid.nextGen();
}
我只是發佈上面,因爲它調用上面的塊,我不想排除任何東西。
我真的不知道還有什麼問題可以解決,但如果有人想看看我項目的完整源代碼,我已經發布了它on pastebin。
什麼行號是堆棧跟蹤中發生的NullPointerException?這將是一個很好的起點。你嘗試過調試嗎?在發生NullPointerException的行之前放入幾個斷點並檢查數組值。 – 2012-01-07 22:54:15
你可以發佈你的錯誤stacktrace? – 2012-01-07 22:54:21