-1

Hello I have the following code:

    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;

and

Worker (String s, Date d, int i){
    workerName = s;
    dateEmployed = d;
    jobsCompleted = i;
}

However it always crashes at the workerList.add, where is my error? Netbeans says "Null Pointer Defference" I do not know what that means... Please help


EDIT! Thanks it fixed it!

Just another quick question

I have also got

   public String toString(){
       return "The worker " + workerName + " has completed "+ jobsCompleted + " jobs";
    }

But but everytime I am calling the toString method it crashes. This is after I create the object.

soumya
  • 3,801
  • 9
  • 35
  • 69
J. Doh
  • 9
  • 3
  • 4
    You've forgotten to assign your list to a List instance: `List workerList = new ArrayList();` – Konstantin Yovkov Sep 03 '15 at 10:59
  • 1
    Why don't you help me instead of saying possible duplicate? You're not doing anybody good @NamanGala – J. Doh Sep 03 '15 at 11:28
  • 2
    We are here to help only. That's why I gave you good stuff from stack overflow which I think you did not refer before. It will clear many concepts. And you can check out answers given by people from SO below! – Naman Gala Sep 03 '15 at 11:30

2 Answers2

4
 ArrayList<Worker> workerList = null;

You initialized it to null. Hence the crash. You need to initialize properly

 ArrayList<Worker> workerList = new ArrayList<Worker>();

And even better with interface programming (Instead of ArrayList on left hand side, declare a List)

 List<Worker> workerList = new ArrayList<Worker>();
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
4

You only need to initialize your list. You create a variable ArrayList<Worker> workerList and fill it with null. Do List<Worker> workerList = new ArrayList<>(); for a correct initialization when declaration or workerList = new ArrayList<>(); if you want to initialize it later after the declaration, which is often usefull. You can read What is a NullPointerException, and how do I fix it? for further information.

Community
  • 1
  • 1
kai
  • 6,702
  • 22
  • 38