Chapter 5 Control Structures: Part 2 213 Fig.
Wednesday, October 31st, 2007Chapter 5 Control Structures: Part 2 213 Fig. 5.7 An example using switch(part 3 of 3). Line 11 in applet SwitchTestdefines instance variable choiceof type int. This variable stores the user s input that determines which type of shape to draw in paint. Method init(lines 14 26) declares local variable inputof type Stringin line 16. This variable stores the Stringthe user types in the input dialog. Lines 19 22 display the input dialog with staticmethod JOptionPane.showInputDialogand prompt the user to enter 1to draw lines, 2to draw rectangles or 3to draw ovals. Line 25 converts input from a Stringto an intand assigns the result to choice. Method paint (lines 29 62) contains a for structure (lines 35 60) that loops 10 times. In this example, the forstructure s header, in line 35, uses zero-based counting. The values of i for the 10 iterations of the loop are 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9, and the loop terminates when i s value becomes 10. [Note: As you know, the applet container calls method paint after methods init and start. The applet container also calls method paint whenever the applet s screen area must be refreshed e.g., after another window that covered the applet s area is moved to a different location on the screen.] Nested in the for structure s body is a switch structure (lines 38 58) that draws shapes based on the integer value input by the user in method init. The switchstructure consists of a series of case labels and an optional default case. When the flow of control reaches the switch structure, the program evaluates the controlling expression (choice) in the parentheses following keyword switch. The program compares the value of the controlling expression (which must evaluate to an integral value of type byte, char, short or int) with each case label. Assume that the user entered the integer 2as his or her choice. The program compares 2with each casein the switch. If a match occurs (case2:), the program executes the statements for that case. For the integer 2, lines 44 47 draw a rectangle, using four arguments, representing the upper left x-coordinate, upper left y-coordinate, width and height of the rectangle, and the switchstructure exits immediately with the breakstatement. Then, the program increments the counter variable in the forstructure and reevaluates the loop-continuation condition to determine whether to perform another iteration of the loop. The breakstatement causes program control to proceed with the first statement after the switchstructure. (In this case, we reach the end of the forstructure s body, so con Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01