Java Reference
In-Depth Information
In Java, the while statement implements such a repetition. The construct
A while statement executes a block of code repeatedly. A condition controls how
often the loop is executed.
while (condition
statement
keeps executing the statement while the condition is true.
228
229
Table 1 Growth of an Investment
Year
Balance
0
$10,000.00
1
$10,500.00
2
$11,025.00
3
$11,576.25
4
$12,155.06
5
$12,762.82
Most commonly, the statement is a block statement, that is, a set of statements
delimited by { } .
In our case, we want to know when the bank account has reached a particular balance.
While the balance is less, we keep adding interest and incrementing the year counter:
while (balance < targetBalance)
{
years++;
double interest = balance * rate / 100;
balance = balance + interest;
}
Here is the program that solves our investment problem:
ch06/invest1/Investment.java
1 /**
2A class to monitor the growth of an investment that
3accumulates interest at a fixed annual rate.
Search WWH ::




Custom Search