Java Reference
In-Depth Information
Also, notice how the statements in Lines 9, 11, and 13, calculate and output the volume
to two, three, and four decimal places.
Note that the value of
PI
printed in Lines 9, 11, 13, and 14 is rounded.
In a format specifier, by using the option width you can also specify the number of
columns to be used to output the value of an expression. For example, suppose
num
is an
int
variable and
rate
is a
double
variable. Furthermore, suppose that:
num = 96;
rate = 15.50;
Consider the following statements:
System.out.println("123456789012345");
//Line 1
System.out.printf("%5d %n", num);
//Line 2
System.out.printf("%5.2f %n", rate);
//Line 3
System.out.printf("%5d%6.2f %n", num, rate);
//Line 4
System.out.printf("%5d %6.2f %n", num, rate);
//Line 5
The output of the statement in Line 1 shows the column positions. The statement in Line
2 outputs the value of
num
in five columns. Because the value of
num
is
96
, we need only
two columns to output the value of
num
. The (default) output is right justified, so the first
three columns are left blank.
The statement in Line 3 outputs the value of
rate
in five columns with two decimal
places. Note that the decimal point also requires a column. That is, the width specifiers
for floating-point values also include a column for the decimal point.
The statements in Lines 4 and 5 output the values of
num
in five columns, followed by the value
of
rate
in six columns with two decimal places. The output of these statements is:
123456789012345
96
15.50
96 15.50
96
15.50
Let us take a close look at the output of the statements in Lines 4 and 5. First, consider the
statement in Line 4, that is:
System.out.printf("%5d%6.2f %n", num, rate);
In this statement, the format string is
"%5d%6.2f %n"
. Notice that there is no space
between the format specifiers
%5d
and
%6.2f
. Therefore, after outputting the value of
num
in the first five columns, the value of
rate
is output starting at column 6 (see the
fourth line of output). Because only five columns are needed to output the value of
rate
and the output is right justified, column 6 is left blank.
Now consider the statement in Line 5. Here, the format string is
"%5d %6.2f %n"
. Notice that
thereisaspacebetweentheformatspecifiers
%5d
and
%6.2f
. Therefore, after outputting the
value of
num
in the first five columns, the sixth column is left blank. The value of
rate
is
Search WWH ::
Custom Search