【发布时间】:2012-02-05 02:56:49
【问题描述】:
我真的不知道是什么导致了这个问题,但是我的程序,应该是康威的生命游戏,在 2 代后崩溃,似乎不管我做什么,我已经尝试了几天来找到错误。
我已将原因缩小到几个可能的领域 - 或者至少,我认为我有。
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 的行之前放置几个断点并检查数组值。
-
您能发布堆栈跟踪信息吗?
标签: java nullpointerexception multidimensional-array conways-game-of-life