构造函数上的空指针异常错误

时间:2014-02-18 01:51:02

标签: java eclipse loops null nested

所以我在这里有一个构造函数,将PandemicModel复制到另一个名为this.grid的网格中。我有一个错误说java.lang.NullPointerException和另一个错误,当我点击Eclipse上的错误时,它突出显示我在嵌套for循环上的最后一个语句。我不知道如何解决这个问题。有什么想法吗?

/**
 * Copy constructor
 * It is assumed that other is not null and that this PandemicModel 
 * is a deep copy of other (i.e., other.grid is copied into a new
 * 2-dim array this.grid)
 * @param other the PandemicModel that is copied
 */
public PandemicModel (PandemicModel other){

    this.rows = other.rows;
    this.columns = other.columns;

    for (int i=0; i<other.rows; i++){
        for (int j=0; j<other.columns; j++){
            this.grid[i][j] = other.grid[i][j];
        }
    }

}

1 个答案:

答案 0 :(得分:0)

我认为@Java Devil暗示,你没有初始化你的网格对象。

您的代码可能需要如下所示:

public PandemicModel (PandemicModel other){

    this.rows = other.rows;
    this.columns = other.columns;

    this.grid = new (Type)[this.rows][this.columns];

    for (int i=0; i<other.rows; i++){
        for (int j=0; j<other.columns; j++){
            this.grid[i][j] = other.grid[i][j];
        }
    }
}

其中Type替换为网格的数据类型。