Formatter and printf |
| INTERMEDIATE |
Sometimes you want more control over printing than System.out.print and System.out.println give
you. For example, you might wish to print numbers in neat columns. The Formatter class
gives you this extra control.
The basic use of a Formatter is as follows:
Formatter f = new Formatter(); f.format(format-string, value, ..., value); System.out.print(f); f.close();
In this code,
values into the format-string according
to its
format specifiers, and adds that string to the formatter.toString() method and prints
the result.If you simply want to print a formatted string, the above can be abbreviated as:
System.out.printf(format-string, value, ..., value);
Here's an example use:
Formatter f = new Formatter(); f.format("The value of %s is %7.4f", "pi", Math.PI); f.format(" and %s is %7.4f.", "e", Math.E); System.out.println(f); f.close();
Output:
The value of pi is 3.1416 and e is 2.7183.
In the above example, a String is substituted for the %s and
a double for
the %7.4f; the double occupies 7 character positions,
4 of them after the decimal point.
A format specifier has the following syntax (illegal spaces added for clarity):
% argument-index$ flags width conversion
The optional argument-index lets you choose which value
(counting from 1, not 0) to put in this place.
The optional width is the number of character positions
to use. For floating point numbers, the syntax totalWidth.fractionWidth specifies
the total number of character positions to use, and the number of digits
after the decimal point.
Here are the available flags (which are optional) and
a few of the possible conversions (one
of which must be present):
flags -left justification #alternate conversion format 0pad with zeros instead of spaces spacepositive numbers are preceded by a space +positive numbers are preceded by a plus sign ,numbers include grouping separators (negative numbers are enclosed in parentheses
conversions %bboolean %ccharacter %dinteger %escientific notation %ffloating point %sstring %tccomplete date and time
%na newline on this platform %%the character %
There is a great deal more to the Formatter class than this.
In particular, there are more than 30 conversions specified for dates and
times.