我有以下 Java 代码来生成用零填充的数字。
DecimalFormat fmt = new DecimalFormat("000");
for (int y=1; y<12; y++)
{
System.out.print(fmt.format(y) + " ");
}
输出如下:
001 002 003 004 005 006 007 008 009 010 011
我的问题是:如何生成带有填充空格而不是前导零的数字?
1 2 3 4 5 6 7 8 9 10 11
注意:我知道 StackOverflow 中有几个问题要求在 String 中填充空格。我知道如何用字符串来做到这一点。我问是否可以使用填充空间格式化 NUMBERS?
最佳答案
for (int y=1; y<12; y++)
{
System.out.print(String.format("%1$4s", y));
}
它将打印长度为 4 的字符串,因此如果 y=1 它将打印 3 个空格和 1,“1”,如果 y 为 10,它将打印 2 个空格和 10, “10”
See the javadocs
https://stackoverflow.com/questions/22541056/