我真的不知道是什么导致了这个问题,但我的程序应该是康威的生命游戏,在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