Java - 为 Conways Game of Life 打印 2D 数组

标签 java

我今天开始编写康威生命游戏的程序。第一步,我只希望用户输入(二次)字段的长度,然后将其显示在屏幕上。但我在 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/

相关文章:

java - block 是 Java 中的语句吗?

java - 552 抱歉,您的信封发件人域必须存在 (#5.7.1)

java - 如何使用vertx和quarkus发布静态集合

java - 在 MySQL 表中存储 Unicode 和特殊字符

java - Int String 格式问题

java - 为什么 web.xml 从 servlet 3.0 中删除

java - 如何获得下周的第一天?

java - JFileChooser getCurrentDirectory 返回错误的当前目录?

java - 将可变长度数据映射到固定结构的最佳方法?

java - 字符串到字节