Conversions and Java Print Streams - Format Modifiers
(Page 3 of 5 )
In addition to a conversion code, the format string can also specify a width, a precision, the argument it’s replaced with, and any of several special-purpose flags. The most general format follows this pattern:
%[argument_index$][flags][width][.precision]conversion
Here is a quick definition of those parameters. More detail on each will follow:
argument_index
The number of the argument with which to replace this tag
flags
Indicators of various formatting options
width
The minimum number of characters with which to format the replacement value
precision
The number of characters after the decimal point; alternately, the maximum number of characters in the formatted string
These four options control exactly how a string is formatted as tags are replaced by values.
Argument index
The argument index is specified when the order of the arguments does not match the order of the tags. For example:
out.printf("There are %2$f centimeters in %1$f feet.", feet, 2.54 * feet * 12);
In this case, indexes start with 1 rather than 0, which is unusual for Java. (The format string counts as argument 0.) If you reference a nonexistent argument,printf()throws aMissingFormatArgumentException.
The argument index is particularly useful when you want to repeat the same value more than once in a string, perhaps formatted differently each time. For example:
System.out.printf("Hexadecimal: %1$H Decimal: %1$f", Math.PI);
You can also repeat the previous argument by specifying a less than sigh (<) rather than an integer and a dollar sign ($). For instance, this statement is equivalent to the previous statement:
System.out.printf("Hexadecimal: %1$H Decimal: %<f", Math.PI);
Next: Flags >>
More Java Articles
More By O'Reilly Media
|
This article is excerpted from chapter seven of Java I/O, Second Edition, written by Elliotte Rusty Harold (O'Reilly, 2006; ISBN: 0596527500). Check it out today at your favorite bookstore. Buy this book now.
|
|