Web server logs - 200 Control Structures: Part 2 Chapter 5 Line

200 Control Structures: Part 2 Chapter 5 Line 21 in the while structure uses Graphics reference g, which refers to the applet s Graphics object, to send the drawLine message to the Graphics object, asking it to draw a line. Remember that sending a message to an object actually means calling a method to perform a task. One of the Graphics object s many services is to draw lines. In previous chapters, we also saw that the Graphics object s other services include drawing rectangles, strings and ovals. Graphics method drawLine requires four arguments, representing the line s first x-coordinate, first y-coordinate, second x-coordinate and second y-coordinate. In this example, the second y-coordinate changes value during each iteration of the loop with the calculation counter*10. This change causes the second point (the end point of the line) in each call to drawLineto move 10 pixels down the applet s display area. Line 22 in the while structure increments the control variable by 1 for each iteration of the loop. The loop-continuation condition in the while structure tests whether the value of the control variable is less than or equal to 10 (the final value for which the condition is true). Note that the program performs the body of this while structure even when the control variable is 10. The loop terminates when the control variable exceeds 10 (i.e., counter becomes 11). The program in Fig. 5.1 can be made more concise by initializing counterto 0 and preincrementing counterin the while structure condition as follows: while ( ++counter <= 10 ) // repetition condition g.drawLine( 10, 10, 250, counter * 10 ); This code saves a statement (and eliminates the need for braces around the loop s body), because the while condition performs the increment before testing the condition. (Remember that the precedence of ++is higher than that of <=.) Coding in such a condensed fashion takes practice. Good Programming Practice 5.1 Programs should control counting loops with integer values. Common Programming Error 5.1 Because floating-point values may be approximate, controlling the counting of loops with floating-point variables may result in imprecise counter values and inaccurate tests for termination. Good Programming Practice 5.2 Indent the statements in the body of each control structure. Good Programming Practice 5.3 Put a blank line before and after each major control structure to make it stand out in the pro- gram. Good Programming Practice 5.4 Too many levels of nesting can make a program difficult to understand. As a general rule, try to avoid using more than three levels of nesting. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Leave a Reply