2017-04-20 19 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