Java Reference
In-Depth Information
1
// Fig. 5.6: Interest.java
2
// Compound-interest calculations with for.
3
4
public class
Interest
5
{
6
public static void
main(String[] args)
7
{
8
double
amount;
// amount on deposit at end of each year
9
double
principal =
1000.0
;
// initial amount before interest
10
double
rate =
0.05
;
// interest rate
11
12
// display headers
13
System.out.printf(
"%s
%20s
%n"
,
"Year"
,
"Amount on deposit"
);
14
15
// calculate amount on deposit for each of ten years
for
(
int
year =
1
; year <=
10
; ++year)
{
// calculate new amount for specified year
amount = principal * Math.pow(
1.0
+ rate, year);
// display the year and the amount
System.out.printf(
"%4d%,20.2f%n"
, year, amount);
}
16
17
18
19
20
21
22
23
24
}
25
}
// end class Interest
Year Amount on deposit
1 1,050.00
2 1,102.50
3 1,157.63
4 1,215.51
5 1,276.28
6 1,340.10
7 1,407.10
8 1,477.46
9 1,551.33
10 1,628.89
Fig. 5.6
|
Compound-interest calculations with
for
.
Formatting Strings with Field Widths and Justification
Line 13 outputs the headers for two columns of output. The first column displays the year
and the second column the amount on deposit at the end of that year. We use the format
specifier
%20s
to output the
String
"Amount
on
Deposit"
. The integer
20
between the
%
and the conversion character
s
indicates that the value should be displayed with a
field
width
of 20—that is,
printf
displays the value with at least 20 character positions. If the
value to be output is less than 20 character positions wide (17 characters in this example),
the value is
right justified
in the field by default. If the
year
value to be output were more
than four character positions wide, the field width would be extended to the right to
accommodate the entire value—this would push the
amount
field to the right, upsetting
the neat columns of our tabular output. To output values
left justified
, simply precede the
field width with the
minus sign (
-
) formatting flag
(e.g.,
%-20s
).