Java的printf使用可变字段大小? [英] Java printf using variable field size?
问题描述
我只是想把一些C代码转换成Java,而且我在 String.printf
中遇到了一些问题。
在C中,为了获得基于变量的特定宽度,我可以使用:
pre $ print $ 当前指数=%* d \ n,sz,指数);
它会将整数格式化为基于 sz
。
尝试:
系统。 out.println(String.format(Current index =%* d \\\
,sz,index));
会导致错误,因为它不像 *
我现在有下面这个kludge:
pre $ System.out.println(String.format(Current index =%+ sz +d \\\
,index));
但是我希望有一个更好的方法,是吗?
在使用
printf
之前声明一个额外的变量: 字符串格式=%+ fieldSize +d;
System.out.printf(format,yourVariables);
(这是我从网络搜索中找到的第一个解决方案)
I'm just trying to convert some C code over to Java and I'm having a little trouble with String.printf
.
In C, to get a specific width based on a variable, I can use:
printf("Current index = %*d\n", sz, index);
and it will format the integer to be a specific size based on sz
.
Trying:
System.out.println(String.format("Current index = %*d\n", sz, index));
results in an error since it doesn't like the *
.
I currently have the following kludge:
System.out.println(String.format("Current index = %" + sz + "d\n", index));
but I'm hoping there's a slightly better way, yes?
Declare an extra variable before using printf
:
String format = "%" + fieldSize + "d";
System.out.printf(format, yourVariables);
(this is the first solution I found from a web search)
这篇关于Java的printf使用可变字段大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!