使用 Javas System.out.format 对齐整数值 [英] Using Javas System.out.format to align integer values
问题描述
我正在尝试生成看起来有点像这样的右对齐数字:
I am trying to produce right aligned numbers looking a bit like this:
12345
2345
但我显然不明白语法.我一直在尝试遵循这些说明.并提出以下尝试(它是整数,所以 d 并且我想要宽度为 7 和 0 的小数):
but I clearly does not understand the syntax. I have been trying to follow these instructions. and Come up with the following attempt (it is integers so d and I want width 7 and 0 decimals):
public class test {
public static void main( String[] args ) {
System.out.format("%7.0d%n", 12345);
System.out.format("%7.0d%n", 2345);
}
}
但无论我做什么,我似乎都以 IllegalFormatPrecisionException
告终.有没有办法使用这个工具来做到这一点?如果不是,你会怎么做?
but no matter what I do I seem to end up with IllegalFormatPrecisionException
. Is there a way to do this using this tool? If not how else would you do it?
推荐答案
你可以这样做:
public class Test {
public static void main( String[] args ) {
System.out.format("%7d%n", 12345);
System.out.format("%7d%n", 2345);
}
}
本质上,这段代码要求 Java 用空格填充字符串,以便输出正好是 7 个字符.
Essentially this code asks Java to pad the string with spaces so that the output is exactly 7 characters.
这篇关于使用 Javas System.out.format 对齐整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!