Chapter 5 Control (Web file server) Structures: Part 2 201 Good

Chapter 5 Control Structures: Part 2 201 Good Programming Practice 5.5 Vertical spacing above and below control structures, and indentation of the bodies of control structures within the control structures headers, gives programs a two-dimensional appearance that enhances readability. 5.3 The forRepetition Structure The for repetition structure handles all of the details of counter-controlled repetition. To illustrate the power of the for structure, let us rewrite the applet of Fig. 5.1. The result is shown in Fig. 5.2. Remember that this program requires a separate HTML document to load the applet into the appletviewer. For the purpose of this applet, the tag specifies a width of 275pixels and a height of 110pixels. 1 // Fig. 5.2: ForCounter.java 2 // Counter-controlled repetition with the for structure 3 4 // Java core packages 5 import java.awt.Graphics; 6 7 // Java extension packages 8 import javax.swing.JApplet; 9 10 public class ForCounter extends JApplet { 11 12 // draw lines on applet s background 13 public void paint( Graphics g ) 14 { 15 // call inherited version of method paint 16 super.paint( g ); 17 18 // Initialization, repetition condition and incrementing 19 // are all included in the for structure header. 20 for ( int counter = 1; counter <= 10; counter++ ) 21 g.drawLine( 10, 10, 250, counter * 10 ); 22 23 } // end method paint 24 25 } // end class ForCounter Fig. 5.2Counter-controlled repetition with the forstructure. Fig. 5. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Leave a Reply