2015-10-04 57 views
-2

我已經重寫了類Object的toString方法,但我的工作不正常,我找不出原因。這裏是我的方法的代碼(在一個名爲ShoppingBag類):我可以不做System.out.println(Item.toString());?

public String toString(){ 
    String str = ""; 
    Item temp = record; 
    str += "\n\nThe bag contains:\n"; 
    str += String.format("%-18s%-13s%-12s\n", "Name of the Items", "Quantity", "Subtotal"); 
    while(temp != null){ 
     str += String.format("%-18s%-13s%-12s\n", temp.getItemName(), temp.getQuantity(), 
      "$"+(temp.getRetailPrice()*temp.getQuantity())); 
    } 
    str += String.format("%-18s%-13s%-12s\n", "", "Total:", "$"+this.totalCost()); 
    str += String.format("%-18s%-13s%-12s\n", "", "Tax(5%):", "$"+(this.totalCost() 
      * taxRate)); 
    str += String.format("%-18s%-13s%-12s\n", "", "Grand Total:", "$"+this.totalCost() 
      +(this.totalCost()*taxRate)); 
    String test = "test1"; 
    return test; 
} 

我知道,那裏面有很多垃圾的一類項目和的String.format。編譯或運行時沒有例外,它只是不打印任何東西。

在我的申請,我試試這個:

ShoppingBag bag = new ShoppingBag(parameters); 
System.out.println(bag.toString()); 

並沒有什麼打印。當我註釋掉除了我的方法的最後兩行(String test = "test1"; return test;)以外的所有內容時,它會打印「test1」,但其他文本塊不應該影響測試變量,所以我不明白爲什麼它不會打印。

+4

什麼時候'臨時'有空'? –

+1

你濫用'toString()'。該方法主要供開發人員在調試時使用。這不是將購物袋的內容打印給用戶。爲此,您應該有一個'print'方法,它將'PrintWriter'作爲參數。這樣編寫者可以將輸出直接傳輸到目標(文件或網絡客戶端)。 'toString()'方法應該簡潔明瞭,只需要足夠的摘要信息來在調試時區分多個行李。 – Andreas

+0

總是顯示不起作用的代碼。我們如何知道你實際上在你的非功能代碼中返回'str'?你會驚訝這種愚蠢的錯誤發生的頻率。 –

回答

5

沒有打印,因爲你陷入了無限循環;這一個:

while(temp != null){ 
    str += String.format("%-18s%-13s%-12s\n", temp.getItemName(), temp.getQuantity(), "$"+(temp.getRetailPrice()*temp.getQuantity())); 
} 

temp從未null所以你永遠擺脫這一循環。

這就是爲什麼當你刪除這些行,它開始工作(你刪除無限循環)。你應該刪除那個while循環。您可能意思是代替if聲明(以避免NullPointerException)。回顧一下,您可能的意思是if (temp != null)而不是while (temp != null)tutorial on while聲明,tutorial on if聲明)。

另外,考慮使用StringBuilder而不是所有的字符串連接。

+0

啊!謝謝,我忘了1行:0​​ temp = temp.getLink();這將temp分配給LinkedList中的下一個變量。 – umbrahunter

相關問題