Java Reference
In-Depth Information
a number followed by a dollar sign as part of the format field. This may be
easier to explain by example; our French translation, switching the order in
which the arguments are used, would be as follows:
String format = "le %2$s %1$s\n";
System.out.printf(format, noun, adjective);
The format field %2$s says to use the second argument from the argument
list—in this case, adjective—as the string that gets formatted here. Similarly,
the format field %1$s says to use the first argument. In effect, the arguments
get reversed without having to change the call to println() , only by translat-
ing the format String . Since such translations are often done in external files,
rather than by assignment statements like we did for our example, it means that
such external files can be translated without modifying the source to move ar-
guments around.
This kind of argument specification can also be used to repeat an argument
multiple times in a format string. This can be useful in formatting Date objects,
where you use the same argument for each of the different pieces that make up
a date—day, month, and so on. Each has its own format, but they can be
combined by repeating the same argument for each piece. One format field
formats the month, the next format field formats the day, and so on. Again an
example may make it easier to see:
import java.util.Date;
Date today = new Date();
System.out.printf("%1$tm / %1$td / %1$ty\n", today);
The previous statement uses the single argument, today , and formats it
in three different ways, first giving the month, then the day of the month, then
the year. The t format indicates a date/time format. There are several suffixes
for it that specify parts of a date, a few of which are used in the example. 9
NOTE
Don't forget the trailing \n at the end of the format string, if you want the output
to be a line by itself.
9. There are many more, familiar to C/C++ UNIX/Linux/POSIX programmers who have used
the strftime() library call.
Search WWH ::




Custom Search