【问题标题】:Break up a string literal over multiple lines将字符串文字拆分为多行
【发布时间】:2017-04-20 00:10:10
【问题描述】:

有没有办法分解一行代码,尽管它在 java 中位于新行,但仍被读取为连续的?

public String toString() {

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

上面的代码当我在一行上做这一切时,一切都很好,但是当我尝试在多行上做这件事时,它就不起作用了。

在 python 中,我知道您使用 \ 开始在新行上输入,但在执行时打印为一行。

用 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中有类似的方法吗?谢谢!

【问题讨论】:

  • 不,在 Java 中无法做到这一点。您能做的最好的事情就是跨行与+ 连接。
  • 你还能用 String.format() 吗,还是必须对每一行都这样做?
  • 如果你需要一个新行concat最后带有/n的字符串。
  • 你不能有多行字符串文字。如果格式在多行之间连接,你仍然可以String.format
  • @Louis Wasserman 作为String 常量表达式的结果,您会在类文件中获得一个String 文字。这实际上是一个多行的 String 文字,你不同意吗?

标签: java string string.format


【解决方案1】:

使用+ 操作符分解新行上的字符串。

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]

【讨论】:

  • 因为只涉及String 文字和常量的多行字符串添加作为单个文字存储在类文件中,所以它准确地完成了所要求的。很好的答案。
  • @LewBloch,感谢您进一步解释和澄清。
  • 谢谢你们!这现在更有意义并理解它!感谢您的澄清!
  • @ProFesh,您可以随时投票并接受您认为有帮助的答案。谢谢:D
【解决方案2】:

遵循 Java 的编码约定:

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

为了便于阅读,在新行的开头总是有连接运算符。

https://www.oracle.com/technetwork/java/javase/documentation/codeconventions-136091.html#248

希望这会有所帮助!

布雷迪

【讨论】:

    猜你喜欢
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 2010-09-15
    相关资源
    最近更新 更多