Using Javas System.out.format to align integer values

↘锁芯ラ 提交于 2019-12-24 10:15:40

问题


I am trying to produce right aligned numbers looking a bit like this:

  12345
   2345

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);
    }
}

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?


回答1:


You can do something like this:

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

Essentially this code asks Java to pad the string with spaces so that the output is exactly 7 characters.




回答2:


Do it like this:

public class test {

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



回答3:


From the linked page, it shows this:

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

You can omit the comma, and change the 8 to a 7




回答4:


converter %d is for integers and %f is for float. "%7.0d%n" is used with a float(i.e., as %7.0f%n) and "%7d%n" is used for integer representation.this is the reason for IllegalFormatPrecisionException exception.

Reference link http://docs.oracle.com/javase/tutorial/java/data/numberformat.html



来源:https://stackoverflow.com/questions/8215282/using-javas-system-out-format-to-align-integer-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!