I\'m trying to create a simple program to take in three items, their quantities, and prices and added them all together to create a simple receipt type format. My professor
System.out.printf("%1$-30s %2$10d %3$10.2f %4$10.2f", "Diet Soda", 10, 1.25, 12.50);
Will print the line
Diet Soda 10 1.25 12.50
The first string passed to the printf
method is a series of format specifiers that describe how we want the rest of the arguments to be printed. Around the format specifiers you can add other characters that will also be printed (without being formatted).
The format specifiers above have the syntax:
%[index$][flags][width][.precision]conversion
where []
denotes optional.
%
begins a formatting expression.
[index$]
indicates the index of the argument that you want to format. Indices begin at 1. The indices above are not actually needed because each format specifier without an index is assigned one counting up from 1.
[-]
The only flag used above, aligns the output to the left.
[width]
indicates the minimum number of characters to be printed.
[.precision]
In this case the number of digits to be written after the decimal point, although this varies with different conversions.
conversion
character(s) indicating how the argument should be formatted. d
is for decimal integer, f
is decimal format for floating points, s
doesn't change the string in our case.
More information can be found here.