2017-04-20 84 views
2

有沒有辦法分解一行代碼,使它被視爲連續的,儘管在java中的新行?分解多行的字符串文字

public String toString() { 

    return String.format("BankAccount[owner: %s, balance: %2$.2f,\ 
    interest rate: %3$.2f,", myCustomerName, myAccountBalance, myIntrestRate); 
    } 

當我做這一切在一行一切正常花花公子,但是當我嘗試這樣做在多行不工作上面的代碼。

在Python中,我知道你使用\來開始在新行上鍵入,但在執行時打印爲一行。

在Python中的一個示例來闡明。在蟒蛇這將打印使用 一個反斜槓或()一行:

print('Oh, youre sure to do that, said the Cat,\ 
if you only walk long enough.') 

用戶會認爲這是:

Oh, youre sure to do that, said the Cat, if you only walk long enough. 

是否有類似的方式在Java中做到這一點?謝謝!

+0

不,沒有辦法做到這一點在Java中。你可以做的最好的做法是通過一行來連接'+'。 –

+0

你還可以String.format()它還是你必須做的每一行? – ProFesh

+0

如果你最後需要一個新行'concat'這個帶有'/ n'的字符串。 –

回答

4

使用+運算符工作分解新行上的字符串。

public String toString() { 
    return String.format("BankAccount[owner: %s, balance: " 
      + "%2$.2f, interest rate:" 
      + " %3$.2f]", 
      myCustomerName, 
      myAccountBalance, myIntrestRate); 
} 

樣本輸出:BankAccount[owner: TestUser, balance: 100.57, interest rate: 12.50]

+1

由於只涉及'字符串'文字和常量的多行字符串添加在類文件中作爲單個文字存儲,因此它完全實現了要求的內容。很好的答案。 –

+0

@LewBloch,謝謝你進一步解釋和澄清。 –

+0

謝謝你們!這現在變得更有意義並且理解它!感謝您的澄清! – ProFesh