Java-打印康威生活游戏的2D数组
我今天开始为康威的人生游戏编程。在第一步中,我只希望用户输入(squadratic)字段的长度,然后显示在屏幕上。但是我在printGrid()方法中得到了一个NullPointerException。以下是必要的代码示例:Java-打印康威生活游戏的2D数组,java,Java,我今天开始为康威的人生游戏编程。在第一步中,我只希望用户输入(squadratic)字段的长度,然后显示在屏幕上。但是我在printGrid()方法中得到了一个NullPointerException。以下是必要的代码示例: public class Grid { private Cell[][]grid; public Grid (int feldlänge) { grid = new Cell[feldlänge][feldlänge]; int x, y; for
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;
}
}
公共类网格{
专用小区[][]网格;
公共电网(内费尔德林格){
网格=新单元[feldlänge][feldlänge];
int x,y;
对于(y=0;y
有点尴尬,我自己找不到错误。我想我忽略了一些简单的事情。
已经非常感谢你的帮助了
更新:已解决!
我只是没有将单元格添加到数组中。它现在可以工作。您似乎没有将单元格添加到网格数组中
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
公共电网(内费尔德林格){
网格=新单元[feldlänge][feldlänge];
int x,y;
对于(y=0;y
您必须将单元格添加到数组中。(德语字段=英语数组)
另外:代替
if( someBoolean){}
if( !someBoolean){}
你应该使用
if( someBoolean){}
else {}
这使代码的作用更加清楚了你从不将你的
单元格
添加到数组中。哦,天哪,非常感谢!我就知道这是件愚蠢的事情!