我今天开始编写康威生命游戏的程序。第一步,我只希望用户输入(二次)字段的长度,然后将其显示在屏幕上。但我在 printGrid() 方法中收到 NullPointerException 。以下是必要的代码示例:
public class Grid {
private Cell[][]grid;
public Grid (int feldlänge) {
grid = new Cell[feldlänge][feldlänge];
int x, y;
for (y = 0; y < feldlänge; y = y + 1) {
for (x = 0; x < feldlänge; x = x + 1) {
Cell cell;
cell = new Cell(x,y);
cell.setLife(false);
} // for
} // for
} // Konstruktor Grid
public String printGrid () {
String ausgabe = "";
int x, y;
for (y = 0; y < grid.length; y = y + 1) {
for (x = 0; x < grid.length; x = x + 1) {
if (grid[x][y].isAlive()) { // Here's the NullPointerException
ausgabe = ausgabe + "■";
}
if (!grid[x][y].isAlive()) {
ausgabe = ausgabe + "□";
}
}
ausgabe = ausgabe + "\n";
}
return ausgabe;
}
public class Cell {
private int x, y;
private boolean isAlive;
public Cell (int pX, int pY) {
x = pX;
y = pY;
} // Konstruktor Cell
public void setLife (boolean pLife) {
isAlive = pLife;
} // Methode setLife
public int getX () {
return x;
} // Methode getX
public int getY () {
return y;
} // Methode getY
public boolean isAlive () {
return isAlive;
}
}
我自己找不到错误,有点尴尬。我想我忽略了一些简单的事情。 非常感谢您的帮助!
更新:已经解决! 我只是没有将单元格添加到数组中。现在可以了。
最佳答案
您似乎没有将单元格添加到网格数组中。
public Grid (int feldlänge) {
grid = new Cell[feldlänge][feldlänge];
int x, y;
for (y = 0; y < feldlänge; y = y + 1) {
for (x = 0; x < feldlänge; x = x + 1) {
Cell cell;
cell = new Cell(x,y);
cell.setLife(false);
grid[x][y] = cell; //put the cell in the grid.
} // for
} // for
} // Konstruktor Grid
关于Java - 为 Conways Game of Life 打印 2D 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42860913/