【问题标题】:Formatting output/Justifying field of width格式化输出/对齐宽度字段
【发布时间】:2017-09-29 22:01:59
【问题描述】:

我必须左对齐站名并右对齐下面示例中的数字结果以进行分配,即 Vegan Station 需要在宽度为 15 的字段中左对齐,但是当我尝试时它给了我结果的 %2d 错误。如果有人能帮助我理解如何正确格式化它,我将不胜感激。

System.out.printf("\n" + "\n" + "You rated each station as follows");

System.out.printf("\n" + "%-15s, Vegan Station" + "%2d", vegan);
System.out.printf("\n" + "Pasta Station " + "%2d" , pasta);
System.out.printf("\n" + "Waffle Station " + "%2s", waffle + "\n");

这是错误:

java.util.MissingFormatArgumentException: Format specifier '%2d'
at java.util.Formatter.format(Formatter.java:2519)
at java.io.PrintStream.format(PrintStream.java:970)
at java.io.PrintStream.printf(PrintStream.java:871)
at Survey.main(Survey.java:127)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

【问题讨论】:

  • 能否包括素食、意大利面和华夫饼的种类?

标签: java format output


【解决方案1】:

你搞砸了你的报价。应该是:

System.out.printf("%n%-15s%2d", "Vegan Station", vegan);

将格式字符串作为单个字符串保存在一起,并将后面的变量放在逗号分隔的列表中。

同样对于新行,不要使用\n,而是在使用 printf 时使用%n

【讨论】:

    猜你喜欢
    • 2012-01-04
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 2016-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多