Formatting Output


float hits=3; float ab=10; String formattedTxt =    String.format("Batting average: %.3f", hits/ab);



In this phrase, we use the format() method to format an output string that prints a baseball batting average in the standard format of three decimal places. The batting average is defined as the number of hits, divided by the number of at-bats, ab. The format specifier %.3f tells the formatter to print the average as a floating point number with three digits following the decimal point.

JDK1.5 introduced the java.util.Formatter class, which can be used to easily format text. The Formatter class works very similar to the printf function in the C language, and provides support for layout justification and alignment, common formats for numeric, string, and date/time data, and locale-specific output. An example of using the Formatter class directly is shown here:

StringBuffer buffer = new StringBuffer(); Formatter formatter = new Formatter(buffer, Locale.US); formatter.format("Value of PI: %6.4f", Math.PI); System.out.println(buffer.toString());


The corresponding output:

Value of PI: 3.1416


In this example, we create a Formatter instance and use it to format the value of the standard mathematical value PI. The value of PI contains an infinite amount of decimal places, but you typically want to restrict it to a small number of decimal places when printing it. In this example, we used the format specifier of %6.4f. The value 6 says that the output for this number should be no more than 6 characters wide, including the decimal point. The value 4 indicates that the precision of the decimal value should be 4 decimal places. Thus the value printed is 6 characters in length and has 4 decimal places: 3.1416.

In addition to using the Formatter class directly, you can use the format() and printf() methods of the System.out and System.err streams. For example, here we print the local time using the format() method on the System.out stream:

System.out.format("Local time: %tT",                    Calendar.getInstance());


This method will print the local time as shown here:

Local time: 16:25:14


The String class also contains a static format() method that can be used to directly format strings. We can use this static method, for example, to easily format a date string as we do here:

Calendar c =    ew GregorianCalendar(1999, Calendar.JANUARY, 6); String s =    String.format(          "Timmy's Birthday: %1$tB %1$te, %1$tY", c);


This will code create the following formatted String value:

Timmy's Birthday: January 6, 1999


All the methods that produce formatted output that we've discussed take a format string and an argument list as parameters. The format string is a String that might contain text and one or more format specifiers. In our birthday formatting example, the format string would be "Timmy's Birthday: %1$tm %1$te,%1$tY". The %1$tm, %1$te, and $1$tY elements are format specifiers. The remainder of the string is static text. These format specifiers indicate how the arguments should be processed and where in the string they should be placed. Referring to our birthday example again, the argument list is just the Calendar object c. Although in this case, we have only one argument, the argument list might contain multiple items. All parameters passed to the formatting methods after the format string are considered arguments.

Format specifiers have the following format:

%[argument_index$][flags][width][.precision]conversion


The argument_index references an argument in the list of arguments passed to the formatting method. The list is indexed starting at 1. So to reference the first argument, you would use 1$.

The flags element is a set of characters that modify the output format. The set of valid flags depends on the conversion.

The width is a nonnegative decimal integer indicating the minimum number of characters to be written to the output.

The precision is a nonnegative decimal integer normally used to restrict the number of characters. The specific behavior depends on the conversion.

The conversion is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument's data type.

All the specifier elements are optional except for the conversion character.

Table 8.1 shows a list of valid conversion characters. For details about date and time conversions, refer to the JavaDoc for the Formatter class at: http://java.sun.com/j2se/1.5.0/docs/api/.

Table 8.1. Formatter Format Codes

Code

Description

b

If the argument arg is null, the result is "false". If arg is a boolean or Boolean, the result is the string returned by String.valueOf(). Otherwise, the result is "true".

h

If the argument arg is null, the result is "null". Otherwise, the result is obtained by invoking Integer.toHexString(arg.hashCode()).

s

If the argument arg is null, the result is "null". If arg implements Formattable, arg.formatTo is invoked. Otherwise, the result is obtained by invoking arg.toString().

c

The result is a Unicode character.

d

The result is formatted as a decimal integer.

o

The result is formatted as an octal integer.

x

The result is formatted as a hexadecimal integer.

f

The result is formatted as a decimal number.

e

The result is formatted as a decimal number in computerized scientific notation.

g

The result is formatted using computerized scientific notation or decimal format, depending on the precision and the value after rounding.

a

The result is formatted as a hexadecimal floating point number with a significand and an exponent.

t

Prefix for date and time conversion characters.

n

The result is the platform-specific line separator.

%

The result is a literal '%'.


Refer to the JavaDoc documentation of the Formatter class for a complete list of the available format codes. This is available at: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net