2013-03-08 86 views
-2

所以我建立一個類是一個存儲爲鏈接列表的字符串。 出於某種原因,每當我嘗試打印出一個字符串時,我都會得到一個NullPointerException。這隻發生在我嘗試打印一個我在第二個構造函數中複製的字符串時。String LinkedList toString()錯誤

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); 




} 

感謝您的幫助!

+2

哪一行是NPE發生的? – smk 2013-03-08 05:50:22

+2

神聖的意大利麪!爲什麼在toString()中使用char []的所有東西?爲什麼不簡單地使用StringBuilder? – 2013-03-08 05:51:01

+0

@Plazsma,學習如何使用'debugger' – Andremoniy 2013-03-08 05:51:10

回答

0

在第二個構造函數中,this.head從不初始化,所以它是null。當您嘗試在toString中訪問它時,您有NullPointerException。

實際上,在第二個構造函數中,您似乎構建了只需扔掉的Node對象,因爲您不會將它們分配給任何對象。你應該真的檢查你的邏輯。

+0

謝謝修復它 – Plazsma 2013-03-08 06:24:53

相關問題