Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

AhmadLang / Java, How To Program, 2004

.pdf
Скачиваний:
626
Добавлен:
31.05.2015
Размер:
51.82 Mб
Скачать

[Page 1342]

28.11. Printing with Argument Indices

An argument index is an optional decimal integer followed by a $ sign that indicates the position of the argument in the argument list. For example, lines 2021 and 2425 in Fig. 28.9 use argument index "1$" to indicate that all format specifiers use the first argument in the argument list. Argument indices enable programmers to reorder the output so that the arguments in the argument list are not necessarily in the order of their corresponding format specifiers. Argument indices also help avoid duplicating arguments. Figure 28.22 demonstrates how to print arguments in the argument list in reverse order using the argument index.

Figure 28.22. Reordering output with argument indices.

1// Fig. 28.22: ArgumentIndexTest

2// Reordering output with argument indices.

4public class ArgumentIndexTest

5{

6public static void main( String args[] )

7{

8System.out.printf(

9"Parameter list without reordering: %s %s %s %s\n",

10"first", "second", "third", "fourth" );

11System.out.printf(

12"Parameter list after reordering: %4$s %3$s %2$s %1$s\n",

13"first", "second", "third", "fourth" );

14} // end main

15} // end class ArgumentIndexTest

Parameter list without reordering: first second third fourth Parameter list after reordering: fourth third second first

[Page 1342 (continued)]

28.12. Printing Literals and Escape Sequences

Most literal characters to be printed in a printf statement can simply be included in the format string. However, there are several "problem" characters, such as the quotation mark (") that delimits the format string itself. Various control characters, such as newline and tab, must be represented by escape sequences. An escape sequence is represented by a backslash (\), followed by an escape character. Figure 28.23 lists the escape sequences and the actions they cause.

Figure 28.23. Escape sequences.

(This item is displayed on page 1343 in the print version)

Escape sequence

Description

 

 

\' (single quote)

Output the single quote (') character.

\" (double quote)

Output the double quote (") character.

\\ (backslash)

Output the backslash (\) character.

\b (backspace)

Move the cursor back one position on the current line.

\f (new page or form

Move the cursor to the start of the next logical page.

feed)

 

\n (newline)

Move the cursor to the beginning of the next line.

\r (carriage return)

Move the cursor to the beginning of the current line.

\t (horizontal tab)

Move the cursor to the next horizontal tab position.

 

 

Common Programming Error 28.4

Attempting to print as literal data in a printf statement a double quote or backslash character without preceding that character with a backslash to form a proper escape sequence might result in a syntax error.

[Page 1342 (continued)]

28.13. Formatting Output with Class Formatter

So far, we have discussed displaying formatted output to the standard output stream. What should we do if we want to send formatted outputs to other output streams or devices, such as a JTextArea or a file? The solution relies on class Formatter (in package java.util), which provides the same formatting capabilities as printf. Formatter is a utility class that enables programmers to output formatted data to a specified destination, such as a file on disk. By default, a Formatter creates a string in memory. Figure 28.24 demonstrates how to use a Formatter to build a formatted string, which is then displayed in a message dialog.

[Page 1343]

Figure 28.24. Formatting output with class Formatter.

1 // Fig. Fig. 28.24: FormatterTest.java 2 // Format string with class Formatter.

3import java.util.Formatter;

4import javax.swing.JOptionPane;

6public class FormatterTest

7{

8public static void main( String args[] )

9{

10// create Formatter and format output

11Formatter formatter = new Formatter();

12formatter.format( "%d = %#o = %#X", 10, 10, 10 );

14// display output in JOptionPane

15JOptionPane.showMessageDialog( null, formatter.toString() );

16} // end main

17} // end class FormatterTest

Line 11 creates a Formatter object using the default constructor, so this object will build a string in memory. Other constructors are provided to allow you to specify the destination to which the formatted

data should be output. For details, see java.sun.com/j2se/5.0/ docs/api/java/util/Formatter.html.

[Page 1344]

Line 12 invokes method format to format the output. Like printf, method format takes a format string and an argument list. The difference is that printf sends the formatted output directly to the standard output stream, while format sends the formatted output to the destination specified by its constructor (a string in memory in this program). Line 15 invokes the Formatter's toString method to get the formatted data as a string, which is then displayed in a message dialog.

String static Method format

Note that class String also provides a static convenience method named format that enables you to create a string in memory without the need to first create a Formatter object. Lines 1112 and line 15 in Fig. 28.24 could have been replaced by

String s = String.format( "%d = %#o = %#^x", 10, 10, 10 );

JOptionPane.showMessageDialog( null, s );

[Page 1344 (continued)]

28.14. Wrap-Up

This chapter summarized how to display formatted output with various format characters and flags. We displayed decimal numbers using format characters d, o, x and X. We displayed floating-point numbers using format characters e, E, f, g and G. We displayed date and time in various format using format characters t and T and their conversion suffix characters. You learned how to display output with field widths and precisions. We introduced the flags +, -, space, #, 0, comma and ( that are used together with the format characters to produce output. We also demonstrated how to format output with class Formatter. In the next chapter, we discuss the String class's methods for manipulating strings. We also introduce regular expressions and demonstrate how to validate user input with regular expressions.

[Page 1344 (continued)]

Summary

Input and output are usually performed with streams, which are sequences of bytes. In input

operations, the bytes flow from a device to main memory. In output operations, bytes flow from main memory to a device.

Normally, the standard input stream is connected to the keyboard, and the standard output stream is connected to the computer screen.

The printf format string describes the formats in which the output values appear. The format specifier consists of argument index, flags, field widths, precisions and conversion characters.

Integers are printed with the conversion characters d for decimal integers, o for integers in octal

form and x (or X) for integers in hexadecimal form. When the conversion character X is used, the output is displayed in uppercase letters.

Floating-point values are printed with the conversion characters e (or E) for exponential notation,

f for regular floating-point notation, and g (or G) for either e (or E) notation or f notation. When the g conversion specifier is indicated, the e conversion character is used if the value is less than

103 or greater than or equal to 107; otherwise, the f conversion character is used. When the conversion characters E and G are used, the output is displayed in uppercase letters.

[Page 1345]

The conversion character c prints a character.

The conversion character s (or S) prints a string of characters. When the conversion character S is used, the output is displayed in uppercase letters.

The conversion character t (or T) followed by a conversion suffix character prints the date and

time in various forms. When the conversion character T is used, the output is displayed in uppercase letters.

Conversion character t (or T) requires the argument to be of type long, Long, Calendar or Date.

Conversion character b (or B) outputs the string representation of a boolean or Boolean. These

conversion characters also output "true" for non-null references and "false" for null references. When conversion character B is used, the output is displayed in uppercase letters.

Conversion character h (or H) returns null for a null reference and a String representation of

the hash code value (in base 16) of the object. Hash codes are used to store and retrieve objects in Hashtables and HashMaps. When conversion character H is used, the output is displayed in uppercase letters.

The conversion character n prints the platform-specific line separator.

The conversion character % is used to display a literal %.

If the field width is larger than the object being printed, the object is right justified in the field by default.

Field widths can be used with all conversion characters except the line-separator conversion.

Precision used with floating-point conversion characters e and f indicates the number of digits that appear after the decimal point. Precision used with floating-point conversion character g

indicates the number of significant digits to appear.

Precision used with conversion character s indicates the number of characters to be printed.

The field width and the precision can be combined by placing the field width, followed by a decimal point, followed by the precision between the percent sign and the conversion character.

The - flag left justifies its argument in a field.

The + flag prints a plus sign for positive values and a minus sign for negative values.

The space flag prints a space preceding a positive value. The space flag and the + flag cannot be used together in an integral conversion character.

The # flag prefixes 0 to octal values and 0x to hexadecimal values.

The 0 flag prints leading zeros for a value that does not occupy its entire field.

The comma (,) flag uses the locale-specific thousands separator (i.e., ',' for U.S. locale) to display integer and floating-point numbers.

The ( flag encloses a negative number in parentheses.

An argument index is an optional decimal integer followed by a $ sign that indicates the position of the argument in the argument list.

Argument indices enable programmers to reorder the output so that the arguments in the

argument list are not necessarily in the order of their corresponding format specifiers. Argument indices also help avoid duplicating arguments.

Class Formatter (in package java.util) provides the same formatting capabilities as printf.

Formatter is a utility class that enables programmers to print formatted output to various destinations, including GUI components, files and other output streams.

Class Formatter's method format outputs formatted data to the destination specified by the Formatter constructor.

The static method format of class String formats data and returns the formatted data as a

String.

[Page 1346]

Terminology

# flag

% conversion character

( flag

+ (plus) flag

- (minus) flag

, (comma) flag

0 (zero) flag

A conversion suffix character a conversion suffix character alignment

argument index

b conversion character

B conversion character

B conversion suffix character b conversion suffix character c conversion character

C conversion suffix character conversion character

d conversion character

D conversion suffix character e conversion character

E conversion character

e conversion suffix character exponential floating-point format f conversion character

F conversion suffix character

field width flag floating-point

floating-point number conversion format method of Formatter format method of String format specifier

format string

Formatter class

g conversion character

G conversion character h conversion character

H conversion character

H conversion suffix character hexadecimal format

I conversion suffix character integer conversion

j conversion suffix character

K conversion suffix character left justification

m conversion suffix character

M conversion suffix character n conversion character

o conversion character octal format

P conversion suffix character p conversion suffix character precision

printf method

r conversion suffix character redirect a stream

right justification rounding

s conversion character

S conversion character

S conversion suffix character scientific notation

space flag

standard error stream standard input stream standard output stream stream

StringBuilder class t conversion character

T conversion character

T conversion suffix character toString method of Formatter x conversion character

Y conversion suffix character y conversion suffix character

Z conversion suffix character