24. Formatted Output

Objectives

In this chapter you’ll learn:

• To understand input and output streams.

• To use printf formatting.

• To print with field widths and precisions.

• To use formatting flags in the printf format string.

• To print with an argument index.

• To output literals and escape sequences.

• To format output with class Formatter.

All the news that’s fit to print.

Adolph S. Ochs

What mad pursuit? What struggle to escape?

John Keats

Remove not the landmark on the boundary of the fields.

Amenehope

Outline

24.1   Introduction

24.2   Streams

24.3   Formatting Output with printf

24.4   Printing Integers

24.5   Printing Floating-Point Numbers

24.6   Printing Strings and Characters

24.7   Printing Dates and Times

24.8   Other Conversion Characters

24.9   Printing with Field Widths and Precisions

24.10   Using Flags in the printf Format String

24.11   Printing with Argument Indices

24.12   Printing Literals and Escape Sequences

24.13   Formatting Output with Class Formatter

24.14   Wrap-Up

24.1 Introduction

An important part of the solution to any problem is the presentation of the results. In this chapter, we discuss the formatting features of method printf and class Formatter (package java.util). Method printf formats and outputs data to the standard output stream—System.out. Class Formatter formats and outputs data to a specified destination, such as a string or a file output stream.

Many features of printf were discussed earlier in the text. This chapter summarizes those features and introduces others, such as displaying date and time data in various formats, reordering output based on the index of the argument and displaying numbers and strings with various flags.

24.2 Streams

Input and output are usually performed with streams, which are sequences of bytes. In input operations, the bytes flow from a device (e.g., a keyboard, a disk drive, a network connection) to main memory. In output operations, bytes flow from main memory to a device (e.g., a display screen, a printer, a disk drive, a network connection).

When program execution begins, three streams are connected to the program automatically. Normally, the standard input stream is connected to the keyboard, and the standard output stream is connected to the screen. A third stream, the standard error stream (System.err), is typically connected to the screen and is used to output error messages so they can be viewed immediately—even when the standard output stream is writing into a file. Operating systems typically allow these streams to be redirected to other devices. Streams are discussed in detail in Chapter 14, Files and Streams, and Chapter 19, Networking.

24.3 Formatting Output with printf

Precise output formatting is accomplished with printf. [Note: Java SE 5 borrowed this feature from the C programming language.] Method printf can perform the following formatting capabilities, each of which is discussed in this chapter:

1. Rounding floating-point values to an indicated number of decimal places.

2. Aligning a column of numbers with decimal points appearing one above the other.

3. Right justification and left justification of outputs.

4. Inserting literal characters at precise locations in a line of output.

5. Representing floating-point numbers in exponential format.

6. Representing integers in octal and hexadecimal format.

7. Displaying all types of data with fixed-size field widths and precisions.

8. Displaying dates and times in various formats.

Every call to printf supplies as the first argument a format string that describes the output format. The format string may consist of fixed text and format specifiers. Fixed text is output by printf just as it would be output by System.out methods print or println. Each format specifier is a placeholder for a value and specifies the type of data to output. Format specifiers also may include optional formatting information.

In the simplest form, each format specifier begins with a percent sign (%) and is followed by a conversion character that represents the data type of the value to output. For example, the format specifier %s is a placeholder for a string, and the format specifier %d is a placeholder for an int value. The optional formatting information is specified between the percent sign and the conversion character. The optional formatting information includes an argument index, flags, field width and precision. We define each of these and show examples of them throughout this chapter.

24.4 Printing Integers

An integer is a whole number, such as 776, 0 or –52, that contains no decimal point. Integer values are displayed in one of several formats. Figure 24.1 describes the integral conversion characters.

Fig. 24.1. Integer conversion characters.

Image

Figure 24.2 prints an integer using each of the integral conversions. In lines 9–10, note that the plus sign is not displayed by default, but the minus sign is. Later in this chapter (Fig. 24.14) we’ll see how to force plus signs to print.

Fig. 24.2. Using integer conversion characters.

Image

The printf method has the form

printf( format-stringargument-list );

where format-string describes the output format, and argument-list contains the values that correspond to each format specifier in format-string. There can be many format specifiers in one format string.

Each format string in lines 8–10 specifies that printf should output a decimal integer (%d) followed by a newline character. At the format specifier’s position, printf substitutes the value of the first argument after the format string. If the format string contained multiple format specifiers, at each subsequent format specifier’s position, printf would substitute the value of the next argument in the argument list. The %o format specifier in line 11 outputs the integer in octal format. The %x format specifier in line 12 outputs the integer in hexadecimal format. The %X format specifier in line 13 outputs the integer in hexadecimal format with capital letters.

24.5 Printing Floating-Point Numbers

A floating-point value contains a decimal point, as in 33.5, 0.0 or -657.983. Floating-point values are displayed in one of several formats. Figure 24.3 describes the floating-point conversions. The conversion characters e and E display floating-point values in computerized scientific notation (also called exponential notation). Exponential notation is the computer equivalent of the scientific notation used in mathematics. For example, the value 150.4582 is represented in scientific notation in mathematics as

1.504582 × 102

and is represented in exponential notation as

1.504582e+02

Fig. 24.3. Floating-point conversion characters.

Image

in Java. This notation indicates that 1.504582 is multiplied by 10 raised to the second power (e+02). The e stands for “exponent.”

Values printed with the conversion characters e, E and f are output with six digits of precision to the right of the decimal point by default (e.g., 1.045921)—other precisions must be specified explicitly. For values printed with the conversion character g, the precision represents the total number of digits displayed, excluding the exponent. The default is six digits (e.g., 12345678.9 is displayed as 1.23457e+07). Conversion character f always prints at least one digit to the left of the decimal point. Conversion characters e and E print lowercase e and uppercase E preceding the exponent and always print exactly one digit to the left of the decimal point. Rounding occurs if the value being formatted has more significant digits than the precision.

Conversion character g (or G) prints in either e (E) or f format, depending on the floating-point value. For example, the values 0.0000875, 87500000.0, 8.75, 87.50 and 875.0 are printed as 8.750000e-05, 8.750000e+07, 8.750000, 87.500000 and 875.000000 with the conversion character g. The value 0.0000875 uses e notation because the magnitude is less than 10-3. The value 87500000.0 uses e notation because the magnitude is greater than 107. Figure 24.4 demonstrates each of the floating-point conversion characters.

Fig. 24.4. Using floating-point conversion characters.

Image

24.6 Printing Strings and Characters

The c and s conversion characters are used to print individual characters and strings, respectively. Conversion character s can also print objects with the results of implicit calls to method toString. Conversion characters c and C require a char argument. Conversion characters s and S can take a String or any Object (this includes all subclasses of Object) as an argument. When an object is passed to the conversion character s, the program implicitly uses the object’s toString method to obtain the String representation of the object. When conversion characters C and S are used, the output is displayed in uppercase letters. The program shown in Fig. 24.5 displays characters, strings and objects with conversion characters c and s. Note that autoboxing occurs at line 10 when an int constant is assigned to an Integer object. Line 15 associates an Integer object argument to the conversion character s, which implicitly invokes the toString method to get the integer value. Note that you can also output an Integer object using the %d format specifier. In this case, the int value in the Integer object will be unboxed and output.

Fig. 24.5. Using character and string conversion characters.

Image

Common Programming Error 24.1

Image

Using %c to print a string causes an IllegalFormatConversionException—a string cannot be converted to a character.

24.7 Printing Dates and Times

With the conversion character t or T, we can print dates and times in various formats. Conversion character t or T is always followed by a conversion suffix character that specifies the date and/or time format. When conversion character T is used, the output is displayed in uppercase letters. Figure 24.6 lists the common conversion suffix characters for formatting date and time compositions that display both the date and the time. Figure 24.7 lists the common conversion suffix characters for formatting dates. Figure 24.8 lists the common conversion suffix characters for formatting times. To view the complete list of conversion suffix characters, visit the website java.sun.com/javase/6/docs/api/java/util/Formatter.html.

Fig. 24.6. Date and time composition conversion suffix characters.

Image

Image

Fig. 24.7. Date formatting conversion suffix characters.

Image

Fig. 24.8. Time formatting conversion suffix characters.

Image

Figure 24.9 uses the conversion character t with the conversion suffix characters to display dates and times in various formats. Conversion character t requires the corresponding argument to be of type long, Long, Calendar or Date (both in package java.util)—objects of each of these classes can represent dates and times. Class Calendar is the preferred class for this purpose because some constructors and methods in class Date are replaced by those in class Calendar. Line 10 invokes static method getInstance of Calendar to obtain a calendar with the current date and time. Lines 13–17, 20–22 and 25–26 use this Calendar object in printf statements as the value to be formatted with conversion character t. Note that lines 20–22 and 25–26 use the optional argument index ("1$") to indicate that all format specifiers in the format string use the first argument after the format string in the argument list. You’ll learn more about argument indices in Section 24.11. Using the argument index eliminates the need to repeatedly list the same argument.

Fig. 24.9. Formatting dates and times with conversion character t.

Image

24.8 Other Conversion Characters

The remaining conversion characters are b, B, h, H, % and n. These are described in Fig. 24.10.

Fig. 24.10. Other conversion specifiers.

Image

Lines 9–10 of Fig. 24.11 use %b to print the value of boolean values false and true. Line 11 associates a String to %b, which returns true because it is not null. Line 12 associates a null object to %B, which displays FALSE because test is null. Lines 13–14 use %h to print the string representations of the hash-code values for strings "hello" and "Hello". These values could be used to store or locate the strings in a Hashtable or HashMap (both discussed in Chapter 16, Collections). Note that the hash-code values for these two strings differ because one string starts with a lowercase letter and the other with an uppercase letter. Line 15 uses %H to print null in uppercase letters. The last two printf statements (lines 16–17) use %% to print the % character in a string and %n to print a platform-specific line separator.

Fig. 24.11. Using the b, B, h, H, % and n conversion characters.

Image

Common Programming Error 24.2

Image

Trying to print a literal percent character using % rather than %% in the format string might cause a difficult-to-detect logic error. When % appears in a format string, it must be followed by a conversion character in the string. The single percent could accidentally be followed by a legitimate conversion character, thus causing a logic error.

24.9 Printing with Field Widths and Precisions

The exact size of a field in which data is printed is specified by a field width. If the field width is larger than the data being printed, the data will be right justified within that field by default. (We demonstrate left justification in Section 24.10.) The programmer inserts an integer representing the field width between the percent sign (%) and the conversion character (e.g., %4d) in the format specifier. Figure 24.12 prints two groups of five numbers each, right justifying those numbers that contain fewer digits than the field width. Note that the field width is increased to print values wider than the field and that the minus sign for a negative value uses one character position in the field. Also, if no field width is specified, the data prints in exactly as many positions as it needs. Field widths can be used with all format specifiers except the line separator (%n).

Fig. 24.12. Right justifying integers in fields.

Image

Common Programming Error 24.3

Image

Not providing a sufficiently large field width to handle a value to be printed can offset other data being printed and produce confusing outputs. Know your data!

Method printf also provides the ability to specify the precision with which data is printed. Precision has different meanings for different types. When used with floating-point conversion characters e and f, the precision is the number of digits that appear after the decimal point. When used with conversion character g, the precision is the maximum number of significant digits to be printed. When used with conversion character s, the precision is the maximum number of characters to be written from the string. To use precision, place between the percent sign and the conversion specifier a decimal point (.) followed by an integer representing the precision. Figure 24.13 demonstrates the use of precision in format strings. Note that when a floating-point value is printed with a precision smaller than the original number of decimal places in the value, the value is rounded. Also note that the format specifier %.3g indicates that the total number of digits used to display the floating-point value is 3. Because the value has three digits to the left of the decimal point, the value is rounded to the ones position.

Fig. 24.13. Using precision for floating-point numbers and strings.

Image

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

printf( "%9.3f"123.456789 );

which displays 123.457 with three digits to the right of the decimal point right justified in a nine-digit field—this number will be preceded in its field by two blanks.

24.10 Using Flags in the printf Format String

Various flags may be used with method printf to supplement its output formatting capabilities. Seven flags are available for use in format strings (Fig. 24.14).

Fig. 24.14. Format string flags.

Image

To use a flag in a format string, place the flag immediately to the right of the percent sign. Several flags may be used in the same format specifier. Figure 24.15 demonstrates right justification and left justification of a string, an integer, a character and a floating-point number. Note that line 9 serves as a counting mechanism for the screen output.

Fig. 24.15. Right justifying and left justifying values.

Image

Figure 24.16 prints a positive number and a negative number, each with and without the + flag. Note that the minus sign is displayed in both cases, but the plus sign is displayed only when the + flag is used.

Fig. 24.16. Printing numbers with and without the + flag.

Image

Figure 24.17 prefixes a space to the positive number with the space flag. This is useful for aligning positive and negative numbers with the same number of digits. Note that the value -547 is not preceded by a space in the output because of its minus sign. Figure 24.18 uses the # flag to prefix 0 to the octal value and 0x to the hexadecimal value.

Fig. 24.17. Using the space flag to print a space before nonnegative values.

Image

Fig. 24.18. Using the # flag with conversion characters o and x.

Image

Figure 24.19 combines the + flag, the 0 flag and the space flag to print 452 in a field of width 9 with a + sign and leading zeros, next prints 452 in a field of width 9 using only the 0 flag, then prints 452 in a field of width 9 using only the space flag.

Fig. 24.19. Printing with the 0 (zero) flag fills in leading zeros.

Image

Figure 24.20 uses the comma (,) flag to display a decimal and a floating-point number with the thousands separator. Figure 24.21 encloses negative numbers in parentheses using the ( flag. Note that the value 50 is not enclosed in parentheses in the output because it is a positive number.

Fig. 24.20. Using the comma (,) flag to display numbers with the thousands separator.

Image

Fig. 24.21. Using the ( flag to place parentheses around negative numbers.

Image

24.11 Printing with Argument Indices

An argument index is an optional integer followed by a $ sign that indicates the argument’s position in the argument list. For example, lines 20–21 and 24–25 in Fig. 24.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 24.22 demonstrates how to print arguments in the argument list in reverse order using the argument index.

Fig. 24.22. Reordering output with argument indices.

Image

24.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 24.23 lists the escape sequences and the actions they cause.

Fig. 24.23. Escape sequences.

Image

Common Programming Error 24.4

Image

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.

24.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 24.24 demonstrates how to use a Formatter to build a formatted string, which is then displayed in a message dialog.

Fig. 24.24. Formatting output with class Formatter.

Image

Image

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/javase/6/docs/api/java/util/Formatter.html.

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.

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 11–12 and line 15 in Fig. 24.24 could have been replaced by

String s = String.format( "%d = %#o = %#^x"101010 );
JOptionPane.showMessageDialog( null, s );

24.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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset