2016-09-13 60 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

相关问题