在多行上分解字符串文字

Pro*_*esh 6 java string string.format

是否有办法打破一行代码,以便尽管在java中的新行上它被读取为连续的?

public String toString() {

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

上面的代码,当我在一行上执行所有操作时,一切都很有效,但是当我尝试在多行上执行此操作时,它不起作用.

在python中,我知道你使用\来开始在新行上键入,但在执行时打印为一行.

Python中的一个例子来澄清.在python中,这将使用反斜杠或()在一行上打印:

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

用户会将此视为:

Oh, youre sure to do that, said the Cat, if you only walk long enough.
Run Code Online (Sandbox Code Playgroud)

在java中有类似的方法吗?谢谢!

Dev*_*ttu 7

使用+运算符工作分解新行上的字符串.

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

样本输出: BankAccount[owner: TestUser, balance: 100.57, interest rate: 12.50]

  • 由于仅涉及“String”文字和常量的多行字符串添加作为单个文字存储在类文件中,因此它准确地完成了所要求的任务。很好的答案。 (2认同)