The complete program is below.
Here is the complete program. Notice how the pieces fit together. The counting loop is nested in the body of the result-controlled loop.
public class MillionDollarInterestRate
{
public static void main( String[] args )
{
double initialAmount = 1000.00 ;
double dollars = 0.0;
double rate = -0.001 ;
while ( dollars < 1000000 )
{
// change to the next rate
rate = rate + 0.001;
// compute the dollars after 40 years at the current rate
int year = 1 ;
dollars = initialAmount;
while ( year <= 40 )
{
dollars = dollars + dollars*rate ; // add another year's interest
dollars = dollars + 1000 ; // add in this year's contribution
year = year + 1 ;
}
}
System.out.println("After 40 years at " + rate*100
+ " percent interest you will have " + dollars + " dollars" );
}
}
Here is a run of the program:
C:\JavaSource\>javac MillionDollarInterestRate.java C:\JavaSource\>java MillionDollarInterestRate After 40 years at 12.600000000000009 percent interest you will have 1021746.3104116677 dollars
The program has some floating point accuracy problems. In practice, financial programs are very carefully written and use floating point with extreme caution. Programming languages intended for business have special data formats for money that ensure that none of it gets lost.
Why is this statement from the program important:
dollars = initialAmount;