Reputation: 511
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?
Upvotes: 0
Views: 106
Reputation: 2772
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
}
Upvotes: 2