| 1 | /** |
| 2 | A class to monitor the growth of an investment that |
| 3 | accumulates interest at a fixed annual rate |
| 4 | */ |
| 5 | public class Investment |
| 6 | { |
| 7 | /** |
| 8 | Constructs an Investment object from a starting balance and |
| 9 | interest rate. |
| 10 | @param aBalance the starting balanece |
| 11 | @param aRate the interest rate in percent |
| 12 | */ |
| 13 | public Investment(double aBalance, double aRate) |
| 14 | { |
| 15 | balance = aBalance; |
| 16 | rate = aRate; |
| 17 | years = 0; |
| 18 | } |
| 19 | |
| 20 | /** |
| 21 | Keeps accumulating interest until a target balance has |
| 22 | been reached. |
| 23 | @param targetBalance the desired balance |
| 24 | */ |
| 25 | public void waitForBalance(double targetBalance) |
| 26 | { |
| 27 | while (balance < targetBalance) |
| 28 | { |
| 29 | years++; |
| 30 | double interest = balance * rate / 100; |
| 31 | balance = balance + interest; |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | Keeps accumulating interest for a given number of years. |
| 37 | @param n the number of years |
| 38 | */ |
| 39 | public void waitYears(int n) |
| 40 | { |
| 41 | for (int i = 1; i <= n; i++) |
| 42 | { |
| 43 | double interest = balance * rate / 100; |
| 44 | balance = balance + interest; |
| 45 | } |
| 46 | years = years + n; |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | Gets the current investment balance. |
| 51 | @return the current balance |
| 52 | */ |
| 53 | public double getBalance() |
| 54 | { |
| 55 | return balance; |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | Gets the number of years this investment has accumulated |
| 60 | interest. |
| 61 | @return the number of years since the start of the investment |
| 62 | */ |
| 63 | public int getYears() |
| 64 | { |
| 65 | return years; |
| 66 | } |
| 67 | |
| 68 | private double balance; |
| 69 | private double rate; |
| 70 | private int years; |
| 71 | } |