Chapter 5 Control Structures: Part 2 207 Similarly, (Web server application)
Chapter 5 Control Structures: Part 2 207 Similarly, the initialization sum =0 could be merged into the initialization section of the forstructure. Good Programming Practice 5.8 Although statements preceding a for structure and statements in the body of a for structure can often be merged into the header of the for structure, avoid doing so, because it makes the program more difficult to read. Good Programming Practice 5.9 Limit the size of control structure headers to a single line. if possible. The next example uses the forstructure to compute compound interest. Consider the following problem: A person invests $1000.00 in a savings account yielding 5% interest. Assuming that all interest is left on deposit, calculate and print the amount of money in the account at the end of each year for 10 years. Use the following formula to determine the amounts: a = p (1 + r) n where p is the original amount invested (i.e., the principal) r is the annual interest rate n is the number of years a is the amount on deposit at the end of the nth year. This problem involves a loop that performs the indicated calculation for each of the 10 years the money remains on deposit. The solution is the application shown in Fig. 5.6. 1 // Fig. 5.6: Interest.java 2 // Calculating compound interest 3 4 // Java core packages 5 import java.text.NumberFormat; 6 import java.util.Locale; 7 8 // Java extension packages 9 import javax.swing.JOptionPane; 10 import javax.swing.JTextArea; 11 12 public class Interest { 13 14 // main method begins execution of Java application 15 public static void main( String args[] ) 16 { 17 double amount, principal = 1000.0, rate = 0.05; 18 19 // create DecimalFormat to format floating-point numbers 20 // with two digits to the right of the decimal point 21 NumberFormat moneyFormat = 22 NumberFormat.getCurrencyInstance( Locale.US ); 23 Fig. 5.6 Calculating compound interest with the forstructure (part 1 of 2). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01