In an old assignment description, I suggested students use the command
asgnPct
has the value 100,
and asgn
has the value 25,
then this will produce the output
As the code shows, System.out has a printf method -- "print formatted". This method takes a String (the format String) that says how the rest of the arguments should be printed. In the sample code, the format String is "%-13s%8d%8d%n". The same format String was used for each of the lines in the table. It says (roughly):
As you probably guessed, it's the % sign that tells printf to do something special. The number after the % sign says how wide to make the field (13 characters, 8 characters), and whether to left-justify (negative number) or right-justify (positive number) in the field. The letter s tells printf that the thing to print is going to be a String. The letter d tells it to print an integer. The letter n tells it to print a newline character.
Any other characters in the format String itself are printed "as is". For example,
The format String from the old assignment
mentions three values to be printed --
a String and two integers.
That means we need to give three more arguments to printf --
the String "Assignments:" and the integers asgnPct
and asgn
.
If only one argument were mentioned
(as in the format String "Here's my message: >%-5s<" above),
then only one more String argument would be provided.
The arguments can be literals
(as the Strings above were)
or variables
(as the integers above were).
printf can also deal with numbers with decimal points. The letter f is used for those, and you can say how many spaces come after the decimal point --
Another thing you can do with numbers (%d and %f) is to say to add "leading zeroes". For that you just put a zero in front of the field width. Thus
Yet another thing you can do with numbers is to add commas in the output. For that you put a comma in front of the field width. Thus
There's plenty more to learn about formatted printing, but that's enuf to get you started. Google java printf for more information.