この問題の原因はわかりませんが、私のプログラムはConwayのGame of Lifeであるはずですが、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
私は2次元配列の境界外のチェック以上、このセクションと仮定していますが、私はそれが実現しなかったことを確認するために予防措置を取ったので、それは、可能ではありません。それでも、これが原因の1つです。
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が発生する行の前にいくつかのブレークポイントを置き、配列の値を調べます。 –
エラーのスタックトレースを投稿できますか? –