2017-09-29 36 views
-1

我必须左对齐站名称并右对齐下例中的数字结果才能进行分配,即纯素食站需要在宽度为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) 
+1

你能否加入素食主义者,意大利面和华夫饼的种类? – jrtapsell

回答

1

你搞乱你的报价。它应该是:

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

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

对于新行,请不要使用\n,而应该在使用printf时使用%n