是否有办法打破一行代码,以便尽管在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中有类似的方法吗?谢谢!
使用+
运算符工作分解新行上的字符串。
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]
遵循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
希望这可以帮助!
布雷迪