将新对象添加到数组时出现NullPointerException

时间:2016-04-10 05:24:06

标签: java nullpointerexception

我正在尝试为剧院座位管理计划添加播放名称和长度。我希望能够添加将在剧院展出的新剧本。目前我对Play类及其子类LocalPlay和ForeignPlay

有以下内容
public class Play {
public String name;
public double length;

public Play(String name, double length){
    this.name = name;
    this.length = length;
}


public void printPlayList(){
    System.out.print("name = " + this.name);
    System.out.print("length - " + this.length);
}   

}


class ForeignPlay extends Play{

public ForeignPlay(String name, double length){
    super(name, length);
}

}

class LocalPlay extends Play{

public LocalPlay(String name, double length){
    super(name, length);
}

}

对于我的Admin类(我希望在其中使用addPlay函数的类),我试图通过传递String和double来向类中添加新对象。这是我的代码:

public class Admin extends User{

private Play [] play;
private int size = 0;

public void addForeignPlay(String name, double length){
    this.play[size] = new ForeignPlay(name,length);
    this.size++;
}

public void addLocalPlay(String name, double length){
    this.play[size] = new LocalPlay(name,length);
    this.size++;
}

public void playDetails(){
    for(int i = 0; i < this.size; i++)
    this.play[i].printPlayList();
}

public static void main (String[] args){
    Admin testAdmin = new Admin();
    testAdmin.addLocalPlay("test", 125);
    testAdmin.playDetails();
}

}

尝试运行时,我希望输出'Test'和125.0。但是,我收到错误消息:

  

线程“main”java.lang.NullPointerException中的异常       在Admin.addLocalPlay(Admin.java:18)       在Admin.main(Admin.java:33)

非常感谢您提供的任何帮助

4 个答案:

答案 0 :(得分:1)

private Play [] play;替换为private Play [] play = new Play[10]; 如果没有初始化数组,则无法在该数组中存储任何值

答案 1 :(得分:0)

Admin课程的建议:

public class Admin extends User {

    private ArrayList<Play> playList = new ArrayList<>();

    public void addForeignPlay(String name, double length) {
        this.playList.add(new ForeignPlay(name, length));
    }

    public void addLocalPlay(String name, double length) {
        this.playList.add(new LocalPlay(name, length));
    }

    public void playDetails() {
        for (int i = 0; i < playList.size(); i++) {
            this.playList.get(i).printPlayList();
        }
    }

    public static void main(String[] args) {
        Admin testAdmin = new Admin();
        testAdmin.addLocalPlay("test", 125);
        testAdmin.playDetails();
    }
}

答案 2 :(得分:0)

在Java中,数组不是动态的(大小是固定的,并在创建时确定)。如果您需要动态数据结构,则应使用ArrayList作为示例。

答案 3 :(得分:0)

您应该初始化播放变量,如

private Play [] play = new Play[100]

或使用构造函数

public Admin(Play[] play, int size) {
    this.play = play;
    this.size = size;
}