-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCompoundInterest.java
54 lines (44 loc) · 1.63 KB
/
CompoundInterest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package CompoundInterest;
/**
* This program shows how to store tabular data in a 2D array.
*
* @author Cay Horstmann
* @version 1.40 2004-02-10
*/
public class CompoundInterest {
public static void main(String[] args) {
final double START_RATE = 10;
final int N_RATES = 6;
final int N_YEARS = 10;
// set interest rates to 10 ... 15%
double[] interestRate = new double[N_RATES];
for (int j = 0; j < interestRate.length; j++)
interestRate[j] = (START_RATE + j) / 100.0;
double[][] balances = new double[N_YEARS][N_RATES];
// set initial balances to 10000
for (int j = 0; j < balances[0].length; j++)
balances[0][j] = 10000;
// compute interest for future years
for (int i = 1; i < balances.length; i++) {
for (int j = 0; j < balances[i].length; j++) {
// get last year's balance from previous row
double oldBalance = balances[i - 1][j];
// compute interest
double interest = oldBalance * interestRate[j];
// compute this year's balance
balances[i][j] = oldBalance + interest;
}
}
// print one row of interest rates
for (int j = 0; j < interestRate.length; j++)
System.out.printf("%9.0f%%", 100 * interestRate[j]);
System.out.println();
// print balance table
for (double[] row : balances) {
// print table row
for (double b : row)
System.out.printf("%10.2f", b);
System.out.println();
}
}
}