2013-11-03 49 views
0

我嘗試輸出我的個人資料從我的對象類中的方法,我記得使用類似於此Outputing字符串中沒有的System.out.println

String output; 
    output = "Name: " + this.Name; 
    output = "Address: " + this.Address; 
    output = "Balance: " + this.balance; 
    output = "Minutes used" + this.minutes; 
    output = "Texts Sent: " + this.texts; 
    output = "Cost per Minute: " + this.unitMinuteCost; 
    output = "Cost per Text: " + this.unitTextCost; 


    return output; 

的方法接力,我認爲我們正在使用某種形式的串建設者我如何輸出所有這些,當我返回輸出

+1

大多數IDE可以爲您生成此方法。 –

回答

2

你可以開始進行串接String值,例如...

String output; 
output = "Name: " + this.Name; 
output += "Address: " + this.Address; 
output += "Balance: " + this.balance; 
output += "Minutes used" + this.minutes; 
output += "Texts Sent: " + this.texts; 
output += "Cost per Minute: " + this.unitMinuteCost; 
output += "Cost per Text: " + this.unitTextCost; 

或者你可以使用StringBuilder爲同樣的任務

StringBuilder output = new StringBuilder(128); 
output.append("Name: ").append(this.Name); 
output.append("Address: ").append(this.Address); 
output.append("Balance: ").append(this.balance); 
output.append("Minutes used").append(this.minutes); 
output.append("Texts Sent: ").append(this.texts); 
output.append("Cost per Minute: ").append(this.unitMinuteCost); 
output.append("Cost per Text: ").append(this.unitTextCost); 

return output.toString(); 

但編譯器會自動爲你做這個。如果在循環中創建輸出,那麼最好使用StringBuilder,因爲編譯器本身不能進行這種優化。

+1

Ouch,一個StringBuilder,附加更多StringBuilders的結果。 –

+0

@PeterLawrey是的,我的壞,複製粘貼 – MadProgrammer

+0

+ 1不漂亮,但更快。順便說一句,如果你用'+'替換'; \ output + =',但是我發現你試圖匹配這個問題,第一個例子會更快/更短。 –

1

所以你想使用StringBuilder? (JavaDoc

StringBuilder output = new StringBuilder(); 
output.append("Name: ").append(this.Name); 
output.append("Address: ").append(this.Address); 

等等

相關問題