我真的不知道是什么导致了这个问题,但是我的程序,应该是康威的生命游戏,在 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();
}
我只是发布上面的内容,因为它调用了上面的块,我不想排除任何事情。
我真的不知道还有什么问题,但以防万一有人想查看我项目的完整源代码,我已将其发布在 pastebin 上。