Reputation: 13
I'm working on a linked list project and needed to write a ListTester that would create a linkedList then using an object adding method that includes a name for each new object should print out the entire list and then print the head (first) name. But what is instead occurring is that it prints half way writes "Exception in thread "main" Actor{ name = EFZASD}" and then continues printing and gives a null pointer exception when trying to print the header.
I have attempted to rewrite the add method several times but does seem to change anything or make it worse
public class ListTester {
public static void main(String args[]){
ActorLinkedList list = new ActorLinkedList();
list.add(new Actor("ADAD"));
list.add(new Actor("ERRER"));
list.add(new Actor("EFZASD"));
list.add(new Actor("GFSXCZ"));
list.add(new Actor("WQWR"));
for (int i = 0; i < list.size(); i++){System.out.println(list.get(i));}
System.out.println(list.head.getName());
}
}
public class ActorLinkedList {
Actor head;
int count;
ActorLinkedList(){
head = null;
}
public ActorLinkedList(Actor head, int count) {
this.head = head;
this.count = count;
}
void add(Actor actor){
Actor node = new Actor();
node.name = actor.getName();
node.next = null;
node.next = head;
head = node;
}
Actor get(int index){
Actor current;
current = head;
for (int i = 0; i < index; i++){
current = current.next;
}
return current;
}
int size(){
Actor current = head;
while (current != null) {
current = current.next;
count++;
}
return count;
}
}
public class Actor {
String name;
Actor next;
Actor(){
next = null;
name = null;
}
Actor (String name){
this.name = name;
this.next = null;
}
String getName() {
return name;
}
void setName (String name){
this.name = name;
}
Actor getNextPtr(){
return this.next;
}
void setNextPtr(Actor next){
this.next = next;
}
@Override
public String toString(){
return "\nActor{ name = " + name + '}';
}
}
My results:
Actor{ name = WQWR}
Actor{ name = GFSXCZ}
Exception in thread "main" Actor{ name = EFZASD}
Actor{ name = ERRER}
Actor{ name = ADAD}
null
java.lang.NullPointerException
at ActorLinkedList.get(ActorLinkedList.java:29)
at ListTester.main(ListTester.java:14)
Expected output:
Actor{ name = WQWR}
Actor{ name = GFSXCZ}
{ name = EFZASD}
Actor{ name = ERRER}
Actor{ name = ADAD}
//printed header here
Upvotes: 1
Views: 44
Reputation: 165
The problem is with your count
variable. It is declared global in your class ActorLinkedList
.
Whenever you are executing list.size()
in the for
loop, your count
is getting incremented by 5 (list's size) added to previous count
value.
This will cause NullPointerException when i
becomes greater than your list size, which it will as count
becomes >25 by the 5th iteration of the for
loop.
To fix it, just reset count
to 0 in your size()
and it will work fine.
int size() {
count = 0;
Actor current = head;
while (current != null) {
current = current.next;
count++;
}
return count;
}
Upvotes: 2