Java Reference
In-Depth Information
Caution
The items must match the format specifiers in exact type. The item for the format
specifier
%f
or
%e
must be a floating-point type value such as
40.0
, not
40
. Thus, an
int
variable cannot match
%f
or
%e
.
Tip
The
%
sign denotes a format specifier. To output a literal
%
in the format string, use
%%
.
Listing 4.6 gives a program that uses
printf
to display a table.
L
ISTING
4.6
FormatDemo.java
1
public class
FormatDemo {
2
public static void
main(String[] args) {
3
// Display the header of the table
4
System.out.printf(
"%-10s%-10s%-10s%-10s%-10s\n"
,
"Degrees"
,
display table header
5
"Radians"
,
"Sine"
,
"Cosine"
,
"Tangent"
);
6
7
// Display values for 30 degrees
8
int
degrees =
30
;
9
double
radians = Math.toRadians(degrees);
10 System.out.printf(
"%-10d%-10.4f%-10.4f%-10.4f%-10.4f\n"
, degrees,
11 radians, Math.sin(radians), Math.cos(radians),
12 Math.tan(radians));
13
14
// Display values for 60 degrees
15 degrees =
60
;
16 radians = Math.toRadians(degrees);
17 System.out.printf(
"%-10d%-10.4f%-10.4f%-10.4f%-10.4f\n"
, degrees,
18 radians, Math.sin(radians), Math.cos(radians),
19 Math.tan(radians));
20 }
21 }
values for 30 degrees
values for 60 degrees
Degrees Radians Sine Cosine Tangent
30 0.5236 0.5000 0.8660 0.5773
60 1.0472 0.8660 0.5000 1.7320
The statement in lines 4-5 displays the column names of the table. The column names are
strings. Each string is displayed using the specifier
%-10s
, which left-justifies the string. The
statement in lines 10-12 displays the degrees as an integer and four float values. The integer is
displayed using the specifier
%-10d
and each float is displayed using the specifier
%-10.4f
,
which specifies four digits after the decimal point.
4.22
✓
✓
What are the format specifiers for outputting a Boolean value, a character, a decimal
integer, a floating-point number, and a string?
Check
Point
4.23
What is wrong in the following statements?
(a)
System.out.printf(
"%5d %d"
,
1
,
2
,
3
);
(b)
System.out.printf(
"%5d %f"
,
1
);
(c)
System.out.printf(
"%5d %f"
,
1
,
2
);
Search WWH ::
Custom Search