[英]Java - printing a 2D array for 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 {}
这使代码更清楚
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.