Professional web hosting - Chapter 5 Control Structures: Part 2 199 1

Chapter 5 Control Structures: Part 2 199 1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition 3 4 // Java core packages 5 import java.awt.Graphics; 6 7 // Java extension packages 8 import javax.swing.JApplet; 9 10 public class WhileCounter 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 int counter = 1; // initialization 19 20 while ( counter <= 10 ) { // repetition condition 21 g.drawLine( 10, 10, 250, counter * 10 ); 22 ++counter; // increment 23 24 } // end while structure 25 26 } // end method paint 27 28 } // end class WhileCounter Fig. 5.1Counter-controlled repetition. Fig. 5. The applet s paint method (that the applet container calls when it executes the applet) operates as follows: The declaration on line 18 names the control variable (counter), declares it to be an integer, reserves space for it in memory and sets it to an initial value of 1. Declarations that include initialization are, in effect, executable statements. The declaration and initialization of countercould also have been accomplished with the declaration and statement int counter; // declare counter counter = 1; // initialize counter to 1 The declaration is not executable, but the assignment statement is. We use both methods of initializing variables throughout this book. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Leave a Reply