Chapter 5 Control Structures: Part 2 211 1 (Cheapest web hosting)

Chapter 5 Control Structures: Part 2 211 1 // Fig. 5.7: SwitchTest.java 2 // Drawing lines, rectangles or ovals based on user input. 3 4 // Java core packages import java.awt.Graphics; 6 7 // Java extension packages 8 import javax.swing.*; 9 public class SwitchTest extends JApplet { 11 int choice; // user’s choice of which shape to draw 12 13 // initialize applet by obtaining user’s choice 14 public void init() { 16 String input; // user’s input 17 18 // obtain user s choice 19 input = JOptionPane.showInputDialog( “Enter 1 to draw linesn” + 21 “Enter 2 to draw rectanglesn” + 22 “Enter 3 to draw ovalsn” ); 23 24 // convert user’s input to an int choice = Integer.parseInt( input ); 26 } 27 28 // draw shapes on applet’s background 29 public void paint( Graphics g ) { 31 // call inherited version of method paint 32 super.paint( g ); 33 34 // loop 10 times, counting from 0 through 9 for ( int i = 0; i < 10; i++ ) { 36 37 // determine shape to draw based on user’s choice 38 switch ( choice ) { 39 case 1: 41 g.drawLine( 10, 10, 250, 10 + i * 10 ); 42 break; // done processing case 43 44 case 2: g.drawRect( 10 + i * 10, 10 + i * 10, 46 50 + i * 10, 50 + i * 10 ); 47 break; // done processing case 48 49 case 3: g.drawOval( 10 + i * 10, 10 + i * 10, 51 50 + i * 10, 50 + i * 10 ); 52 break; // done processing case 53 Fig. 5.7 An example using switch(part 1 of 3). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Leave a Reply