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

AhmadLang / Java, How To Program, 2004

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

[Page 1327 (continued)]

28.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, etc.).

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 to the screen so they can be viewed immediatelyeven 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 24, Networking.

[Page 1328]

28.3. Formatting Output with printf

Precise output formatting is accomplished with printf. [Note: J2SE 5.0 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. (See Appendix E, Number Systems, for more information on octal and hexadecimal values.)

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.

[Page 1328 (continued)]

28.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 28.1 describes the integral conversion characters.

Figure 28.1. Integer conversion characters.

Conversion character

Description

 

 

d

Display a decimal (base 10) integer.

o

Display an octal (base 8) integer.

x or X

Display a hexadecimal (base 16) integer. X causes the digits 09

 

and the letters AF to be displayed and x causes the digits 09

 

and af to be displayed.

 

 

Figure 28.2 prints an integer using each of the integral conversions. In lines 910, note that the plus sign is not displayed by default, but the minus sign is. Later in this chapter (Fig. 28.14) we will see how to force plus signs to print.

[Page 1329]

Figure 28.2. Using integer conversion characters.

1// Fig. 28.2: IntegerConversionTest.java

2// Using the integral conversion characters.

4public class IntegerConversionTest

5

{

6

public static void main( String args[] )

7{

8System.out.printf( "%d\n", 26 );

9System.out.printf( "%d\n", +26 );

10System.out.printf( "%d\n", -26 );

11System.out.printf( "%o\n", 26 );

12System.out.printf( "%x\n", 26 );

13System.out.printf( "%X\n", 26 );

14} // end main

15} // end class IntegerConversionTest

26

26 -26 32 1a 1A

The printf method has the form

printf( format-string, argument-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 810 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.

[Page 1329 (continued)]

28.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 28.3 describes the floating-point conversions. The conversion character e and E displays 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 x 102

Figure 28.3. Floating-point conversion characters.

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

Conversion character

Description

 

 

 

 

e

or

E

Display a floating-point value in exponential notation. When

 

 

 

conversion character E is used, the output is displayed in

 

 

 

uppercase letters.

f

 

 

Display a floating-point value in decimal format.

g

or

G

Display a floating-point value in either the floating-point format

 

 

 

f or the exponential format e based on the magnitude of the

 

 

 

value. If the magnitude is less than 10 3, or greater than or

 

 

 

equal to 10 7, the floating-point value is printed with e (or E).

 

 

 

Otherwise, the value is printed in format f. When conversion

 

 

 

character G is used, the output is displayed in uppercase letters.

a

or

A

Display a floating-point number in hexadecimal format. When

 

 

 

conversion character A is used, the output is displayed in

 

 

 

uppercase letters.

 

 

 

 

[Page 1330]

and is represented in exponential notation as

1.504582e+02

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 character 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 floatingpoint 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 28.4 demonstrates each of the floating-point conversion characters.

Figure 28.4. Using floating-point conversion characters.

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

1// Fig. 28.4: FloatingNumberTest.java

2// Using floating-point conversion characters.

4public class FloatingNumberTest

5

{

6

public static void main( String args[] )

7{

8System.out.printf( "%e\n", 12345678.9 );

9System.out.printf( "%e\n", +12345678.9 );

10System.out.printf( "%e\n", -12345678.9 );

11System.out.printf( "%E\n", 12345678.9 );

12System.out.printf( "%f\n", 12345678.9 );

13System.out.printf( "%g\n", 12345678.9 );

14System.out.printf( "%G\n", 12345678.9 );

15} // end main

16} // end class FloatingNumberTest

1.234568e+07

1.234568e+07 -1.234568e+07 1.234568E+07

12345678.900000

1.23457e+07

1.23457E+07

[Page 1330 (continued)]

28.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 character c and C requires a char argument. Conversion character 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. 28.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.

[Page 1331]

Figure 28.5. Using character and string conversion characters.

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

1

//

Fig. 28.5: CharStringConversion.java

2

//

Using character and string conversion characters.

3

 

 

4public class CharStringConversion

5{

6

public static void main(

String args[]

)

7

{

 

 

8

char character = 'A';

// initialize

char

9String string = "This is also a string"; // String object

10Integer integer = 1234; // initialize integer (autoboxing)

12System.out.printf( "%c\n", character );

13System.out.printf( "%s\n", "This is a string" );

14System.out.printf( "%s\n", string );

15System.out.printf( "%S\n", string );

16System.out.printf( "%s\n", integer ); // implicit call to toString

17} // end main

18} // end class CharStringConversion

A

This is a string

This is also a string THIS IS ALSO A STRING 1234

Common Programming Error 28.1

Using %c to print a string causes an Illegal FormatConversionExceptiona string cannot be converted to a character.

[Page 1331 (continued)]

28.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 28.6 lists the common conversion suffix characters for formatting date and time compositions that display both the date and the time. Figure 28.7 lists the common conversion suffix characters for formatting dates. Figure 28.8 lists the common conversion suffix characters for formatting times. To view the complete list of conversion suffix characters, visit the Web site java.sun.com/j2se/5.0/docs/api/java/util/Formatter.html.

Figure 28.6. Date and time composition conversion suffix characters.

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

Conversion

 

suffix character

Description

 

 

c

Display date and time formatted as

 

day month date hour:minute:second time-zone year

 

with three characters for day and month, two digits for date, hour, minute

 

and second and four digits for yearfor example, Wed Mar 03 16:30:25

 

GMT-05:00 2004. The 24-hour clock is used. In this example, GMT-05:00 is

 

the time zone.

F

Display date formatted as year-month-date with four digits for the year

 

and two digits each for the month and the date (e.g., 2004-05-04).

D

Display date formatted as month/day/year with two digits each for the

 

month, day and year (e.g., 03/03/04).

r

Display time formatted as hour:minute:second AM|PM with two digits

 

each for the hour, minute and second (e.g., 04:30:25 PM). The 12-hour

 

clock is used.

R

Display time formatted as hour:minute with two digits each for the hour

 

and minute (e.g., 16:30). The 24-hour clock is used.

T

Display time formatted as hour:minute:second with two digits for the

 

hour, minute and second (e.g., 16:30:25). The 24-hour clock is used.

 

 

[Page 1333]

Figure 28.7. Date formatting conversion suffix characters.

Conversion

suffix character Description

A

Display full name of the day of the week (e.g., Wednesday).

a

Display the three-character short name of the day of the week (e.g.,

 

Wed).

B

Display full name of the month (e.g., March).

b

Display the three-character short name of the month (e.g., Mar).

d

Display the day of the month with two digits, padding with leading zeros

 

as necessary (e.g., 03).

m

Display the month with two digits, padding with leading zeros as

 

necessary (e.g., 07).

e

Display the day of month without leading zeros (e.g., 3).

Y

Display the year with four digits (e.g., 2004).

y

Display the last two digits of the year with leading zeros as necessary

 

(e.g., 04).

j

Display the day of the year with three digits, padding with leading zeros

 

as necessary (e.g., 016).

 

 

Figure 28.8. Time formatting conversion suffix characters.

Conversion

 

suffix character

Description

 

 

H

Display hour in 24-hour clock with a leading zero as necessary (e.g.,

 

16).

I

Display hour in 12-hour clock with a leading zero as necessary (e.g.,

 

04).

k

Display hour in 24-hour clock without leading zeros (e.g., 16).

l

Display hour in 12-hour clock without leading zeros (e.g., 4).

M

Display minute with a leading zero as necessary (e.g., 06).

S

Display second with a leading zero as necessary (e.g., 05).

Z

Display the abbreviation for the time zone (e.g., GMT-05:00, stands

 

for Eastern Standard Time, which is 5 hours behind Greenwich Mean

 

Time).

P

Display morning or afternoon marker in lower case (e.g., pm).

p

Display morning or afternoon marker in upper case (e.g., PM).

 

 

Figure 28.9 uses the conversion character t together 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 1317, 2022 and 2526 use this Calendar object in printf statements as the value to be formatted with conversion character t. Note that lines 2022 and 2526 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 will learn more about argument indices in Section 28.11. Using the argument index eliminates the need to repeatedly list the same argument.

[Page 1334]

Figure 28.9. Formatting dates and times with conversion character t.

1

//

Fig. 28.9:

DateTimeTest.java

2

//

Formatting

dates and times with conversion character t and T.

3

import

java.util.Calendar;

4

 

 

 

 

5

public

class

DateTimeTest