0

Main Class:

ArrayList<LinkedList> my_lists = new ArrayList<LinkedList>();

    try {
        Scanner sc = new Scanner(file);
        while (sc.hasNextLine()) {

            String line = sc.nextLine();
            LinkedList the_list = new LinkedList();
            String[] templist = line.split("\\s*,\\s*");

            for(int i=0; i<templist.length; i++){
                temp = templist[i];
                the_list.add(temp);
                System.out.println(templist[i]);
            }

            my_lists.add(the_list);
            System.out.println(line);
        }
        sc.close();
    } 

Add method from my LinkedList class:

    public void add (Object newData){
    Node cache = head;
    Node current = null;
    while ((current = cache.next) != null)
        cache = cache.next;

    cache.next = new Node(newData,null);
}

It's giving me an error everytime I run this for the line: the_list.add(temp); Any ideas on what's going on?

1
  • 2
    What is the specific error/stack trace that's returned? Commented Mar 20, 2014 at 13:37

1 Answer 1

2

If you're getting a NullPointerException, it probably because you haven't initialized the head variable in your class. The first time you go to add an Object to your LInkedLIst, you call the add method and head is null; Thus, cache = null and you then try to reference cache.next in the while loop, which throws an Exception.

Try adding this to the beginning of your add method to handle the special case.

if (head == null)
head = new Node(newData, null);
else {
  .. rest of method 
}
Sign up to request clarification or add additional context in comments.

4 Comments

I had that at the top of my code, just not copied to stackexchange. I moved it to the beginning of my loop and same error still. I'm pretty sure it's something within the the_list.add(temp; line
What is the full Exception/stack trace?
Yep. Please remember to accept answers as well if they best answered your question.
Done :) Just had to wait on the timer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.