2017-02-15 41 views

回答

1

您的級聯結束前取出分號。

String output = "If you borrow" + currencyFormatter.format(loanAmount) 
    +" at an interest rate of" + rate + "%" 
    +"\nfor" + years 
    +",you will pay" + totalInterest + "in interest."; 

我還建議您將連接運算符移動到行的末尾而不是行的開始位置。這是一種較小的文體偏好...

String output = "If you borrow" + currencyFormatter.format(loanAmount) + 
    " at an interest rate of" + rate + "%" + 
    "\nfor" + years + 
    ",you will pay" + totalInterest + "in interest."; 

最後,您可能會注意到,當您嘗試打印該字符串時缺少一些空格。 String.format方法對此有幫助(另請參閱Formatter的文檔)。它比做大量的連接還要快。

String output = String.format(
    "If you borrow %s at an interest rate of %d%%\nfor %d years, you will pay %d in interest.", currencyFormatter.format(loanAmount), rate, years, totalInterest 
); 
相關問題