Db0987 Db0987 - 3 years ago 157
Java Question

Formatting output/Justifying field of width

I have to left-justify the station names and right-justify the number results in the example below for an assignment, ie Vegan Station needs to be left-justified in a field of width 15, but when I try it gives me an error for the %2d for the result. If anyone could help me understand how to correctly format it I'd really appreciate it.

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


Here's the error:

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)

Answer Source

You're messing up your quotes. It should be:

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

Keep the format String together as a single String, and the variables to follow in a comma-delimited list.

Also for new lines, don't use \n but rather use %n when using printf.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download