所以我这里有一个构造函数,它将EpidemicModel复制到另一个名为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];
}
}
}
我认为正如@Java魔鬼所暗示的那样,您没有初始化网格对象。
您的代码可能需要如下所示:
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
替换为网格的数据类型。