Java 1.5 Tiger A Developers Notebook [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Java 1.5 Tiger A Developers Notebook [Electronic resources] - نسخه متنی

David Flanagan, Brett McLaughlin

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید








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);



The String versions of these methods are static.

This should look awfully familiar if you just read "Writing Formatted Output".
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:


String balanceStmt =
String.format("Remaining account balance: $%(,6.2f"+
"(Today's total balance: $%(,<8.2f)", balance);

This saves a few steps, and now the balanceStmt String can be output
easily. This method is even more useful for the stream and writer versions:


System.out.format("Date: %tD%nTime: %<tr%n", System.currentTimeMillis( ));



/ 131