Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 构造函数上出现空指针异常错误_Java_Eclipse_Loops_Null_Nested - Fatal编程技术网

Java 构造函数上出现空指针异常错误

Java 构造函数上出现空指针异常错误,java,eclipse,loops,null,nested,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

我这里有一个构造函数,它将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];
        }
    }

}

我认为正如@javadevil所暗示的,您并没有初始化网格对象

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

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];
        }
    }
}

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

什么是网格?它已经初始化了吗?不管是这样还是那样,堆栈跟踪和这些字段的声明在这里都是非常宝贵的。grid、this和other都是在一个抽象类中声明和初始化的。此方法只是继承了抽象类的所有字段和方法的类的一部分;人们不能阅读java异常,这让我一直感到惊讶!即使没有进一步的信息,您也可以打印this.grid和other以及other.grid并找出哪一个是空的!哦,好的。我现在明白了,非常感谢!!:成功了!