具有可变间距的格式化输出

时间:2014-08-18 15:57:33

标签: java printf

是否有支持在javas printf方法的标志中使用变量的功能,例如

printf("%nd", 12);

其中 n 是变量吗?

我想在printf方法中指定间距 ,例如

int n = 5;
System.out.printf("%nd", 12);

而不是以下

System.out.printf("%5d", 12);

或者,是否有类似的内置功能?

3 个答案:

答案 0 :(得分:2)

您不需要将间距作为数据的一部分传递 您可以在printf()语句中动态构建格式字符串,如下所示:

int n = 5;
System.out.printf("%"+n+"d", 12);

答案 1 :(得分:1)

是的。存在于java System.out.printf("The date is %d/%d/%d", 1,2,1997);

答案 2 :(得分:0)

使用String.format()

根据需要构建格式字符串,然后传递给String.format()。格式字符串和参数列表的使用与其在printf()

中的使用相同
String myFormat = "...." // build this string with the format you need
String output = String.format( myFormat, ...);
相关问题