2014-03-27 75 views
0

好吧,我已經完成了這個程序,但是現在我迷了路。我返回空指針(它在第44行說,但這只是一個while循環),我需要幫助修復它。我使用鏈表來實現我的隊列,而其他兩個類都通過100%,所以最終的類(CarQueue)是創建空指針的問題所在。我的隊列中的空指針(鏈接列表)

public class CarQueue<E> { 

    private LinkNode<E> head; 
    private LinkNode<E> tail; 

    public CarQueue() { 
     head = null; 
     tail = null; 
    } 

    public CarQueue(E newData) { 
     LinkNode<E> temp = new LinkNode<E>(newData, null); 
     head = temp; 
     tail = temp; 
    } 

    public void addToQueue(E newData) { 
     LinkNode<E> temp = new LinkNode<E>(newData, null); 
     if (empty() == false) { 
      tail.setNext(temp); 
      tail = temp; 
     } else { 
      head = temp; 
      tail.setNext(temp); 
      tail = temp; 
     } 
    } 

    public String toString() { 
     LinkNode<E> temp = head; 
     String cars = ""; 
     while (temp.getNext() != null) { 
      cars += temp.toString() + '\n'; 
     } 
     return cars; 
    } 

    public E removeFmQueue() { 
     LinkNode<E> headReturn = head; 
     head = head.getNext(); 
     return headReturn.getData(); 

    } 

    public LinkNode<E> peek() { 
     return head.getNext(); 
    } 

    public boolean empty() { 
     if (head == null) 
      return true; 
     else 
      return false; 
    } 
} 
+0

嚴格執行我的規範,我被告知要設置一個空的構造函數,其中head是null,是的,但在我的第二個構造函數頭中應該是temp節點的值。第二個構造函數設置爲隊列中有一個元素,因此頭部和尾部都是temp。根據我的測試,雖然(temp.getNext()!= null)拋出異常,但getNext很好,它是在我的LinkNode類中設置的,它完美地工作並通過了所有測試。我不確定爲什麼我會得到完全無效的。希望這有助於 – user3466773

回答

1

如果

while (temp.getNext() != null) { 

是拋出異常的行,然後temp爲空,(或者,如果它甚至有可能,getNext()被扔NullPointerException)。但我們假設temp是問題。

temp正被分配到head,所以head被分配到null

如果調用零參數構造函數,但在調用toString()之前沒有調用其他函數,那麼確實會導致temp被指定爲null。因此,當您嘗試temp.getNext()時,會拋出NullPointerException

爲了防止這種情況,你可以有由toString()方法返回一個替代值:

public String toString() { 
    if(head == null) { 
     return "no head. I got nothing."; 
    } 

    //print the other stuff... 
} 

但是,真的,最好的解決辦法是絕不允許的頭 - 因此溫度 - 爲空,因爲這意味着你的班級處於不穩定和基本無法使用的狀態。

最明顯的方法來防止這種情況是消除零參數的構造函數 - 或可替換地擁有它只有呼叫中的其他構造與非空值 - 並確保其他構造從未讓頭仍然爲空。

+0

我需要遵循後者的解決方案,但我不知道是什麼讓我的頭變爲空或我的頭應該改爲 – user3466773

+0

我無法刪除該構造函數。當我和他一起工作時,我的老師讓我設置它,所以這是我作業的一部分。 – user3466773

+0

再次更新我的答案。 – aliteralmind