9.3 Using the format( ) Convenience Method
The Formatter object is a nice
addition to the languagehowever, it's a
bit inconvenient to break your program flow for four or five statements
related only to formatting, and then get back to the job at hand. It's even
more distracting when you have to do this five or six times in a single
code block. Fortunately, there are some nice convenience methods that
make these steps largely unnecessary.
9.3.1 How do I do that?
The classes java.io.PrintStream, java.io.PrintWriter, and java.lang.String all have a new method available to them in Tiger, called format( ).
All three classes have two versions of the method:
public [returnType] format(String format, Object... args);
public [returnType] format(Locale l, String format, Object... args);
|
For each of these,
returnType
is the object type itself (so a
PrintStream, PrintWriter, or String). For both PrintStream and
PrintWriter, the output is usually ignored; for String, the method is
usually invoked statically and the result is assigned to a new String.
Each method used varargs, as did the Formatter object, allowing you to
pass in as many arguments to be used by the format string as needed.So, rather than having to create a new Formatter, set one of these
objects as its sink, and format it, you can handle all of this in a single
step:
This saves a few steps, and now the balanceStmt String can be output
String balanceStmt =
String.format("Remaining account balance: $%(,6.2f"+
"(Today's total balance: $%(,<8.2f)", balance);
easily. This method is even more useful for the stream and writer versions:
System.out.format("Date: %tD%nTime: %<tr%n", System.currentTimeMillis( ));