需要帮助来了解NullPointerException

时间:2019-12-06 15:48:31

标签: java class

这行代码给了我一个错误。

Scanner sce = new Scanner(new File("employees.txt"));

while(sce.hasNextLine()) {
    String[] obj = sce.nextLine().split(", ");
    Employee e = new Employee(obj);
    department d = new department(e); //Here is where the error pops up (Main.java:29)
    ...
}

我正在扫描文本文件,并将不同的字段拆分为字符串数组,然后从Employee类声明一个对象。然后,我使用department类的对象声明Employee类的对象,然后遇到此错误:

Exception in thread "main" java.lang.NullPointerException
    at ssst.edu.ba.department.<init>(department.java:19)
    at ssst.edu.ba.Main.main(Main.java:29)

我的department班:

package ssst.edu.ba;

import java.util.ArrayList;

public class department {
    private ArrayList<Employee> Marketing;
    private ArrayList<Employee> Production;
    private String department;

    public department() {
    }

    public department(String department) {
        this.department = department;
    }

    public department(Employee employee) {
        if(employee.getDepartment() == "Marketing") Marketing.add(employee);
        else Production.add(employee); //This is the other location (department.java:19)
    }

    public String getDepartment() {
        return department;
    }

    public ArrayList<Employee> getMarketing() {
        return Marketing;
    }

    public ArrayList<Employee> getProduction() {
        return Production;
    }
}

文件 employees.txt 如下:

Ginny, Gullatt, Marketing, 1000
Tiara, Curd, Production, 1200
amie, Poorman, Marketing, 900
Jammie, Hasson, Marketing, 800
Lionel, Hailey, Marketing, 500
Genevive, Mckell, Production, 2000
Esteban, Slaubaugh, Marketing, 1300
Elden, Harte, Production, 1340
Tasia, Rodrigue, Marketing, 1200
Nathanial, Dentler, Production, 1700
Valda, Nicoletti, Marketing, 600
Kary, Wilkerson, Production, 600
Coletta, Akey, Marketing, 800
Wilmer, Jack, Production, 600
Loreta, Agnew, Marketing, 700
Suzy, Cleveland, Production, 1450
Pasty, Laprade, Marketing, 1300
Candie, Mehaffey, Production, 1800
Glady, Landman, Marketing, 1900
Tierra, Mckeown, Production, 2200

2 个答案:

答案 0 :(得分:1)

我会说你只是忘记实例化列表

private ArrayList<Employee> marketing;

在构造函数中

marketing = new ArrayList<Employee>();

另一方面,变量名应以小写字母开头。大写字母用于类名。

答案 1 :(得分:0)

arraylist Production和Marketing都未初始化。在构造函数中,您应该初始化所有类变量。另外,将字符串与.equals()

进行比较
lines()

编辑:“营销” .equals()可以防止克里斯托弗指出的空指针异常