gpt4 book ai didi

java - 二维数组和空指针异常 (Java)

转载 作者:行者123 更新时间:2023-12-02 00:32:07 24 4
gpt4 key购买 nike

我真的不知道是什么导致了这个问题,但我的程序(应该是康威的生命游戏)在两代后崩溃了,似乎无论我做什么,我已经尝试了好几天来找到错误。

我已将原因缩小到几个可能的领域 - 或者至少,我认为我已经做到了。

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();
}

我只是发布上面的内容,因为它调用了上面的 block ,并且我不想排除任何可能性。

我真的不知道问题可能是什么,但为了以防万一有人想查看我的项目的完整源代码,我已经发布了它 on pastebin .

最佳答案

在下一代中你会:

 //avoiding null pointer errors
if (matrix[j][i] == null) matrix[j][i] = false;

numNeighbors() 中的所有 if 执行相同的操作

short numNeighbors(int x, int y) {
short numNeighbors;
numNeighbors = 0;
if(x > 0 && y > 0 && matrix[x][y] != null){
if (matrix[j][i] != null && matrix[x+1][y] == true) numNeighbors++;
if (matrix[j][i] != null && matrix[x][y+1] == true) numNeighbors++;
if (matrix[j][i] != null && [x+1][y+1] == true) numNeighbors++;
if (matrix[j][i] != null && matrix[x][y-1] == true) numNeighbors++;
if (matrix[j][i] != null && matrix[x-1][y] == true) numNeighbors++;
if (matrix[j][i] != null && matrix[x+1][y-1] == true) numNeighbors++;
if (matrix[j][i] != null && matrix[x-1][y+1] == true) numNeighbors++;
if (matrix[j][i] != null && matrix[x-1][y-1] == true) numNeighbors++;
}
return numNeighbors;
}

或者甚至更好地将所有单元格预实例化为 false。

//Run in constructor
for(int i ..
for(int j ..
matrix[j][i] = false

关于java - 二维数组和空指针异常 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8773765/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com