我今天开始编写Conways Game of Life。第一步,我只希望用户输入(中队(字段的长度,然后显示在屏幕上。但是我在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
您必须将单元格添加到数组中。(德语字段 = 英语数组(
另外:代替
if( someBoolean){}
if( !someBoolean){}
你应该使用
if( someBoolean){}
else {}
这使得代码的作用更加清晰