Java Reference
In-Depth Information
This revision is wrong. Can you find the reason? See Checkpoint Question 4.21 for the
answer.
4.8.2 Case Study: Predicting the Future Tuition
Suppose that the tuition for a university is $10,000 this year and tuition increases 7% every
year. In how many years will the tuition be doubled?
Before you can write a program to solve this problem, first consider how to solve it by
hand. The tuition for the second year is the tuition for the first year * 1.07 . The tuition for a
future year is the tuition of its preceding year * 1.07 . Thus, the tuition for each year can be
computed as follows:
double tuition = 10000 ; int year = 0 ; // Year 0
tuition = tuition * 1.07 ; year++; // Year 1
tuition = tuition * 1.07 ; year++; // Year 2
tuition = tuition * 1.07 ; year++; // Year 3
...
Keep computing the tuition for a new year until it is at least 20000 . By then you will know
how many years it will take for the tuition to be doubled. You can now translate the logic into
the following loop:
double tuition = 10000 ;
// Year 0
int year = 0 ;
while (tuition < 20000 ) {
tuition = tuition * 1.07 ;
year++;
}
The complete program is shown in Listing 4.10.
L ISTING 4.10 FutureTuition.java
1 public class FutureTuition {
2
public static void main(String[] args) {
3
double tuition = 10000;
// Year 0
4
int year = 0 ;
5
6 tuition = tuition * 1.07 ;
7 year++;
8 }
9
10 System.out.println( "Tuition will be doubled in "
11 + year + " years" );
12 System.out.printf( "Tuition will be $%.2f in %1d years" ,
13 tuition, year);
14 }
15 }
while (tuition < 20000 ) {
loop
next year's tuition
Tuition will be doubled in 11 years
Tuition will be $21048.52 in 11 years
The while loop (lines 5-8) is used to repeatedly compute the tuition for a new year. The
loop terminates when the tuition is greater than or equal to 20000 .
 
Search WWH ::




Custom Search