2011-11-21 55 views
1

我试图产生右对齐的数字看起来有点像这样:使用Java类System.out.format对齐整数值

12345 
    2345 

,但我显然不明白的语法。我一直在努力遵循these instructions。并提出了以下尝试(它是整数所以d,我想宽7个0小数):

public class test { 

    public static void main(String[] args) { 
     System.out.format("%7.0d%n", 12345); 
     System.out.format("%7.0d%n", 2345); 
    } 
} 

但无论我做什么,我似乎与IllegalFormatPrecisionException结束了。有没有办法使用这个工具来做到这一点?如果不是,你会怎么做呢?

+0

'.0'是浮点数。你不需要它。 –

回答

3

你可以做这样的事情:

public class Test { 
    public static void main(String[] args) { 
     System.out.format("%7d%n", 12345); 
     System.out.format("%7d%n", 2345); 
    } 
} 

本质上讲,这代码询问Java来垫用空格字符串,使输出正好是7个字符。

+1

+1:你不需要空间。我会使用'%n'而不是'\ n' –

+0

@PeterLawrey这也可以。谢谢。 –

+2

+1将类名更改为正确大写 –

1

做这样的:

public class test { 

    public static void main(String[] args) { 
     System.out.format("%7d%n", 12345); 
     System.out.format("%7d%n", 2345); 
    } 
} 
1

从链接的页面,它显示了这一点:

System.out.format("%,8d%n", n); // --> " 461,012"

可以省略逗号,并改变8到7