我已經重寫了類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」,但其他文本塊不應該影響測試變量,所以我不明白爲什麼它不會打印。
什麼時候'臨時'有空'? –
你濫用'toString()'。該方法主要供開發人員在調試時使用。這不是將購物袋的內容打印給用戶。爲此,您應該有一個'print'方法,它將'PrintWriter'作爲參數。這樣編寫者可以將輸出直接傳輸到目標(文件或網絡客戶端)。 'toString()'方法應該簡潔明瞭,只需要足夠的摘要信息來在調試時區分多個行李。 – Andreas
總是顯示不起作用的代碼。我們如何知道你實際上在你的非功能代碼中返回'str'?你會驚訝這種愚蠢的錯誤發生的頻率。 –