将对象添加到数组 - nullPointException

时间:2017-06-22 19:14:27

标签: java nullpointerexception

在我的任务中,我有2个班Kadry(人员)和Pracownik(工人)。 Pracownik看起来像这样(带有getter和setter):

public class Pracownik {

private String name;
private String lastName;
private double salary;
private char gender;
private int structure;

public Pracownik( String name, String lastName, double salary, char gender, int structure) {
    this.name = name;
    this.lastName = lastName;
    this.salary = salary;
    this.gender = gender;
    this.structure = structure;

在Kadry类中有字段private Pracownik[] workersprivate int employment(保存实际的工作数),初始化字段的构造函数。还有一种方法可以将一个worker添加到列表中,这一点就是我遇到麻烦的地方,因为我不断得到NullPointException。我的班级卡德里看起来像这样:

public class Kadry {
private Pracownik[] workers_;
private int employement_;

public Kadry () {
    Pracownik[] workers_ = new Pracownik[100];
    employement_ = workers_.length;
}
public void addWorker(Pracownik p) {
    for (int i = 0; i < 100; i++) {
       if (workers_[i] == null) {
           workers_[i] = p;
           break;
       }
       else System.out.println("List is already full!!!");
    }
}

public static void main(String[] args) {
    Kadry k1 = new Kadry();
    Pracownik Piotr = new Pracownik("Piotr", "Wanjas", 3000.00, 'M', 3);
    k1.addWorker(Piotr);
    System.out.println(k1.workers_[0].getName());

    }
}

NullPointException显示在第if (workers_[i] == null) {

0 个答案:

没有答案