2016-09-13 62 views
0

有沒有辦法使用轉義序列打印變量,類似於Swift(如下所示)?您可以使用轉義序列打印Java變量嗎?

var variable = 0 print("The number \(variable) is cool!")

是的,我知道有其他的方法來完成相同的目標,但我想縮短代碼,並避免怪物如

String variable = "0"; 
System.out.print("The number" + variable + "is cool!"); 

我也想避免不必解析家居它來打印不同類型的

+0

不,Java缺少字符串插值功能。 – dasblinkenlight

回答

3
System.out.print("The number " + variable + " is cool!"); 

System.out.printf("The number %s is cool!", variable); 

System.out.printf(MessageFormat.format("The number {0} is cool!", variable)); 

更多的選擇比是不可能到現在爲止...

+1

你錯過了'printf'上的'f',我想提到['MessageFormat'](https://docs.oracle.com/javase/8/docs/api/java/text/MessageFormat.html)會也是適當的。 – Andreas

0

由於Java字符串逃逸的當前版本是不可能的,你可以使用,無論printf函數這表現如下

System.out.printf("The number %d is cool!", variable); 

%d符號告訴程序尋找一個整數變量。 可以找到符號的完整列表here

相關問題