我正在处理一个链表项目,需要编写一个ListTester来创建一个链表,然后使用一个对象添加方法(其中包括每个新对象的名称)应打印出整个列表,然后打印头部(first)名称。但是发生的是,它在打印"Exception in thread "main" Actor{ name = EFZASD}"的过程中打印了一半,然后继续打印,并在尝试打印标题时给出了空指针异常。
我试图几次重写add方法,但似乎确实改变了任何东西或使其变得更糟
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 + '}';
}
}
我的结果:
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)
预期产量:
Actor{ name = WQWR}
Actor{ name = GFSXCZ}
{ name = EFZASD}
Actor{ name = ERRER}
Actor{ name = ADAD}
//printed header here
分析解答
问题出在您的count
变量上。它在ActorLinkedList
类中声明为全局。
每当您在for
循环中执行list.size()
时,您的count
都会增加5(列表的大小),并添加到先前的count
值中。
当i
变得大于列表大小时,这将导致NullPointerException,当count
变为列表大小时for
循环的第5次迭代> 25。
要解决此问题,只需将size()
中的count
重置为0,它将正常工作。
int size() {
count = 0;
Actor current = head;
while (current != null) {
current = current.next;
count++;
}
return count;
}