您好我有以下代码:
java.util.Date date = new java.util.Date();
ArrayList<Worker> workerList = null;
//Create Worker
System.out.println ("You have selected create worker. \n" + "please enter a name for the worker.\n");
//Create new worker object
scanner.nextLine();
String tName = scanner.nextLine();
Worker newWorker = new Worker (tName, date, 0);
workerList.add(newWorker);
wCurrent = newWorker;
和
Worker (String s, Date d, int i){
workerName = s;
dateEmployed = d;
jobsCompleted = i;
}
然而它总是在workerList.add崩溃,我的错误在哪里?
Netbeans说"Null Pointer Defference"
我不知道这意味着什么......请帮忙
修改! 谢谢它修好了!
另一个快速问题
我也有
public String toString(){
return "The worker " + workerName + " has completed "+ jobsCompleted + " jobs";
}
但是每当我调用toString方法时它都会崩溃。这是在我创建对象之后。
答案 0 :(得分:4)
ArrayList<Worker> workerList = null;
您将其初始化为null。因此崩溃。你需要正确初始化
ArrayList<Worker> workerList = new ArrayList<Worker>();
使用界面编程更好(而不是左侧的ArrayList,声明一个List)
List<Worker> workerList = new ArrayList<Worker>();
答案 1 :(得分:4)
您只需要初始化列表。您创建变量ArrayList<Worker> workerList
并将其填入null
。请在声明时List<Worker> workerList = new ArrayList<>();
进行正确初始化,如果要在声明后稍后初始化它,请workerList = new ArrayList<>();
,这通常很有用。您可以阅读What is a NullPointerException, and how do I fix it?了解更多信息。