-2

所以我正在构建一个类,它是一个存储为链表的字符串。出于某种原因,每当我尝试打印出一个字符串时,我都会得到一个NullPointerException. 这只发生在我尝试打印我在第二个构造函数中复制的字符串时。

class Node
{
char c;
Node next;
int index;
}

public class StringLink {

int len;
Node head= new Node();
public StringLink(String init)
{
   head.index=0;
   Node temp= head;
   len=init.length();
   int i=0;
   while (i<this.len)
   {
     Node n= new Node();
     n.c=init.charAt(i);
     n.index=i+1;
     temp.next=n;
     temp=n;
     i++;
   }


}

// constructor -- initialize object with another StringLink    
public StringLink(StringLink other)
{
   Node temp=other.head;
   temp=temp.next;
   len=other.length();
   for (int i=0; i<this.len; i++)
   {
     Node n= new Node();
     n.c= temp.c;
     n.index=i+1;
     if (temp.next!=null){
       temp=temp.next;
       n.next=temp;
     }
     else n.next=null;

   }
}

这是不起作用的 toString() 方法:

 public String toString()
{
  char[] narr= new char[this.len];
  Node temp= new Node();
  temp=this.head;
  temp=temp.next;
  System.out.println(temp.c);
  for (int i=0; i<this.len;i++)
  {
    narr[i]=temp.c;
    System.out.println(narr[i]);
    if (temp.next!=null)
      temp=temp.next;

  }
  return new String(narr);




}

谢谢你的帮助!

4

1 回答 1

0

在第二个构造函数中,this.head永远不会初始化,所以它是null. 当您尝试在 中访问它时toString,您会遇到 NullPointerException。

实际上,在第二个构造函数中,您似乎构建了只是丢弃的 Node 对象,因为您没有将它们分配给任何东西。你真的应该检查你的逻辑。

于 2013-03-08T05:56:54.000 回答