Formatter and printf
Sometimes you want more control over printing than
you. For example, you might wish to print numbers in neat columns. The
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,
format-stringaccording 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();
The value of pi is 3.1416 and e is 2.7183.
In the above example, a
String is substituted for 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
argument-index lets you choose which value
(counting from 1, not 0) to put in this place.
width is the number of character positions
to use. For floating point numbers, the syntax
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
of which must be present):
alternate conversion format
pad with zeros instead of spaces
positive numbers are preceded by a space
positive numbers are preceded by a plus sign
numbers include grouping separators
negative numbers are enclosed in parentheses
complete date and time
a newline on this platform
There is a great deal more to the
Formatter class than this.
In particular, there are more than 30 conversions specified for dates and