2014-09-19 48 views
0

我想創建並在循環排序的鏈接列表中插入數字,但我得到一個錯誤,因爲 行號中的空指針異常。 45. plzz任何人都可以看到我在這裏做錯了什麼。創建並在java中的排序鏈接列表中插入數字

public class nodes { 
    private int data; 
    private nodes next; 

    public nodes(int data){ 
     this.data = data; 
    } 

    //standard getters and setters. See below if you really want to 

    public static void main (String args[]) throws IOException{ 
     BufferedReader br =new BufferedReader(new InputStreamReader(System.in)); 
     System.out.println("enter 0 to stop"); 
     nodes headnode =null; 

     int n =Integer.parseInt(br.readLine()); 
     while(n!=0){ 
      nodes insert = null; 
      System.out.println("enter the value"); 

      int t =Integer.parseInt(br.readLine()); 
      insert.setdata(t); 

      nodetoinsert(insert, headnode); 
     } 
    } 

    private static void nodetoinsert(nodes p, nodes headnode){ 
     nodes previousnode =null; 

     if (headnode ==null){ 
      headnode.setdata(p.getdata()); 
     }else if(headnode.getdata()>(p.getdata())){ 
      p.setNext(headnode); 
     }else{ 
      nodes currentnode= headnode.getnext(); 

      if(currentnode.getnext() == null) 
       currentnode.setNext(headnode); 

      while(currentnode.getdata()<= p.getdata()&& currentnode !=headnode){ 
       previousnode =currentnode; 
       currentnode =currentnode.getnext(); 
      } 

      previousnode.setNext(p); 
      p.setNext(currentnode); 
     } 
    } 

    public void setdata(int data){ 
     this.data=data; 
    } 

    public int getdata(){ 
     return data; 
    } 

    public void setNext(nodes next){ 
     this.next=next; 
    } 

    public nodes getnext(){ 
     return this.next; 
    } 
} 
+0

請標記第45行。我想你的問題是這裏:'nodes insert = null;'然後'insert.setdata(t);',這可能會拋出異常。但你也可以發佈一致的堆棧跟蹤。 – pzaenger 2014-09-19 08:51:08

+3

這是java。我建議你寫一個以大寫字母開頭的類名,比如'Nodes'。 Methos(「對象的功能」)通常寫成camelCase。你的'nodetoinsert'會變成'nodeToInsert'。它更易讀,像Eclipse這樣的IDE可以更好地處理它。想知道更多嗎?這裏是指導方針:http://www.oracle.com/technetwork/java/codeconventions-135099.html – Atmocreations 2014-09-19 08:59:41

回答

0
if (headnode ==null){ 

    headnode.setdata(p.getdata()); 

} 

你呼籲headnode SetData方法,其是空=> NPE。與插入節點相同。

+0

thnks幫助其工作,但現在我有一個新的錯誤 – 2014-09-19 13:15:37

0

這裏有兩個問題: 1)nodes headnode =null;

這仍然被作爲NULL傳遞給nodetoinsert(insert, headnode); 初始化headnode。 nodes headnode =new nodes(0);

2)您正嘗試在空引用上調用方法。請參閱如下:

while(n!=0){ 
      **nodes insert = null;** 
      System.out.println("enter the value"); 

      int t =Integer.parseInt(br.readLine()); 
      **insert**.setdata(t); 

      nodetoinsert(insert, headnode); 
     } 

您的節點引用變量未初始化。您需要初始化該節點引用。如下所示:

while(n!=0){ 
      nodes insert = new nodes(0); 
      System.out.println("enter the value"); 

      int t =Integer.parseInt(br.readLine()); 
      insert.setdata(t); 

      nodetoinsert(insert, headnode); 
     } 

讓我知道你是否想要任何進一步的幫助。