13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

80Chapter 3An Experienced Programmer’s Introducti<strong>on</strong> to Javaa number followed by a dollar sign as part of the format field. This may beeasier to explain by example; our French translati<strong>on</strong>, switching the order inwhich 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 sec<strong>on</strong>d argument from the argumentlist—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 argumentsget reversed without having to change the call to println(), <strong>on</strong>ly by translatingthe format String. Since such translati<strong>on</strong>s are often d<strong>on</strong>e in external files,rather than by assignment statements like we did for our example, it means thatsuch external files can be translated without modifying the source to move argumentsaround.This kind of argument specificati<strong>on</strong> can also be used to repeat an argumentmultiple 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 upa date—day, m<strong>on</strong>th, and so <strong>on</strong>. Each has its own format, but they can becombined by repeating the same argument for each piece. One format fieldformats the m<strong>on</strong>th, the next format field formats the day, and so <strong>on</strong>. Again anexample 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 itin three different ways, first giving the m<strong>on</strong>th, then the day of the m<strong>on</strong>th, thenthe year. The t format indicates a date/time format. There are several suffixesfor it that specify parts of a date, a few of which are used in the example. 9NOTED<strong>on</strong>’t forget the trailing \n at the end of the format string, if you want the outputto be a line by itself.9. There are many more, familiar to C/C++ UNIX/<strong>Linux</strong>/POSIX programmers who have usedthe strftime() library call.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!