Bài giảng Chapter 5: Selection Statements

Tài liệu Bài giảng Chapter 5: Selection Statements: Chapter 5Selection Statements©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 5 ObjectivesAfter you have read and studied this chapter, you should be able toImplement selection control in a program by using if statements.Implement selection control in a program by using switch statements.Write boolean expressions with relational and boolean operators.Evaluate given boolean expressions correctly.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 5 Objectives, cont.After you have read and studied this chapter, you should be able toNest an if statement inside another if statement’s then or else part correctly.Describe how objects are compared.Choose the appropriate selection control statement for a given task.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.1 The if StatementStatements in programs are executed in sequence. We can add decision-making statements to a program to alter...

ppt76 trang | Chia sẻ: honghanh66 | Lượt xem: 916 | Lượt tải: 0download
Bạn đang xem trước 20 trang mẫu tài liệu Bài giảng Chapter 5: Selection Statements, để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên
Chapter 5Selection Statements©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 5 ObjectivesAfter you have read and studied this chapter, you should be able toImplement selection control in a program by using if statements.Implement selection control in a program by using switch statements.Write boolean expressions with relational and boolean operators.Evaluate given boolean expressions correctly.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 5 Objectives, cont.After you have read and studied this chapter, you should be able toNest an if statement inside another if statement’s then or else part correctly.Describe how objects are compared.Choose the appropriate selection control statement for a given task.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.1 The if StatementStatements in programs are executed in sequence. We can add decision-making statements to a program to alter the control flow.The statement that alters the control flow is called a control statement. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.1 The if StatementThe if statement is one type of selection statement. InputHandler input = new InputHandler(); int testScore = input.getInteger(“Enter test score:”); if (testScore ) else ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.1 The if StatementThe is a conditional expression that is evaluated to either true or false.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 5.1Mapping of the sample if statement to the general format.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.1 The if StatementThe six relational operators we can use in conditional expressions are: greater than>= greater than or equal to©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 5.2The diagram showing the control flow of the sample if statement.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.1 The if StatementThe if statement does not have to contain a block of code for the else condition. In the if-then structure, no special instructions are executed if the boolean expression evaluates to false. if (testScore >=95){ JOptionPane.showMessageDialog(“You are an honor student”);} else { }©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 5.3The diagram showing the control flow of the second version of the if statement. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.2 Boolean Expressions and VariablesA boolean operator takes boolean values as its operands and returns a boolean value. The three boolean operators areand: &&or: ||not !©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.2 Boolean Expressions and VariablesBoolean operators and their meanings:©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.2 Boolean Expressions and VariablesThe result of a boolean expression is either true or false. These are the two values of data type boolean. We can declare a variable of data type boolean and assign a boolean value to it.boolean pass, done;pass = 70 = 70){ if (studentAge =70 and age >=10 }} else { //test score ){ : ... : }©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.5 The switch StatementThe data type of must be char, byte, short, or int. The value of is compared against the constant i of . If there is a matching case, its case body is executed. Otherwise, the execution continues to the statement following the switch statement. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.5 The switch StatementThe break statement causes execution to skip the remaining portion of the switch statement and resume execution following the switch statement. The break statement is necessary to execute statements in one and only one case.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 5.7A diagram showing the control flow of the switch statement with and without the break statements.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.5 The switch StatementIt is good practice to implement a default case in a switch statement. The default case will be executed if there is no matching case. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.6 Drawing GraphicsWe introduce four standard classes related to drawing geometric shapes on a window:java.awt.Graphicsjava.awt.Colorjava.awt.Pointjava.awt.Dimension©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.6 Drawing GraphicsWe can draw geometric shapes on a frame window by calling appropriate methods of the java.awt.Graphics class.//g is a Graphics object:g.drawRect(50, 50, 100, 30);©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 5.8How the position of the rectangle is determined by the drawRect method.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 5.9The distinction between the draw and fill methods. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.6 Drawing GraphicsThe java.awt.Color class allows us to designate the color of an object.The RGB scheme combines three values ranging from 0 to 255 for red, green, and blue. Color pinkColor;pinkColor = new Color(255,175,175)©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.6 Drawing GraphicsThere are public class constants defined in the Color class for common colors:Color.blackColor.blueColor.greenColor.magentaColor.orangeand so on.g.setColor(Color.blue);g.drawRect(50, 50, 100, 30);©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 5.10A frame with a white background content pane and two colored squares.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.6 Drawing GraphicsA java.awt.Point object designates a point in two-dimensional space.Point pt = new Point();pt.x = 10;pt.y = 20;assigns the position (10, 20).©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.6 Drawing GraphicsThe java.awt.Dimension class can be used to create bounding rectangles that surround shapes. Dimension dim = new Dimension();dim.width = 40;dim.height = 70;©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 5.11Bounding rectangles of various shapes.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing ShapesWrite an application that simulates a screensaver by drawing various geometric shapes in different colors. The user has an option of choosing a type (ellipse or rectangle), color, and movement (stationary, smooth, or random).©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 5.12Two types of predefined classes: The first type requires us to use the predefined classes by calling their methods. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 5.12, cont.Two types of predefined classes: The second type requires us to define helper classes for the predefined classes we want to use.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing ShapesProgram flow:Get the shape the user wants to draw.Get the color of the chosen shape.Get the type of movement the user wants to use.Start the drawing.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing ShapesProgram implementation:Start with a program skeleton. Explore the DrawingBoard class.Define an experimental DrawableShape class that draws a dummy shape.Add code to allow the user to select a shape. Extend the DrawableShape and other classes as necessary.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing ShapesAdd code to allow the user to specify the color. Extend the DrawableShape and other classes as necessary.Add code to allow the user to specify the motion type. Extend the DrawableShape and other classes as necessary.Finalize the code by tying up loose ends.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 5.13The program diagram for the Ch5DrawShape program.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing ShapesStep 1 Development: Program SkeletonUse the DrawingBoard class to establish a launch pad for the development.Keep the code simple at this stage: Make the shape visible on the screen.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapes/** * Chapter 5 Sample Development: Drawing Shapes (Step 1) * * The instantiable main class of the program. */class Ch5DrawShape {/** The DrawingBoard object for simulating screensaver */ private DrawingBoard canvas; public Ch5DrawShape( ) { canvas = new DrawingBoard( ); } ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapespublic static void main( String[] args ) { Ch5DrawShape screensaver = new Ch5DrawShape(); screensaver.start(); } public void start( ) { canvas.setVisible(true); }}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing ShapesStep 2 Development: Draw a ShapeDefine the DrawableShape class with the specified set of methods:public void draw (java.awt.Graphics)public java.awt.Point getCenterPoint()public java.awt.Dimension getDimension ()public void setCenterPoint (java.awt.Point)©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapesimport java.awt.*;/** * Step 2: Add a preliminary DrawableShape class * * A class whose instances know how to draw themselves.*/class DrawableShape { private Point centerPoint;public DrawableShape( ) { centerPoint = null; }©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapespublic void draw(Graphics g) { g.setColor(Color.blue); g.fillOval(centerPoint.x-100, centerPoint.y-100, 200, 200); }public Point getCenterPoint( ) { return centerPoint; } public Dimension getDimension( ) { return new Dimension(200,200); } public void setCenterPoint(Point point) { centerPoint = point; }}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing ShapesThe Ch5DrawShape class with the modified start method:import java.awt.*;/** * Chapter 5 Sample Development: Start drawing shapes (Step 2) * * The instantiable main class of the program. */class Ch5DrawShape {... public void start( ) { DrawableShape shape1 = new DrawableShape(); DrawableShape shape2 = new DrawableShape(); DrawableShape shape3 = new DrawableShape(); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapes shape1.setCenterPoint(new Point(250,300)); shape2.setCenterPoint(new Point(500,300)); shape3.setCenterPoint(new Point(750,300)); canvas.addShape(shape1); canvas.addShape(shape2); canvas.addShape(shape3); canvas.setMovement(DrawingBoard.SMOOTH); canvas.setVisible(true); canvas.start(); }...}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing ShapesStep 3 Development: Allow the User to Select a ShapeUse JOptionPane to allow the user to input a choice numerically, and to establish the height and width of the shape.Modify the DrawableShape class so it can draw three different geometric shapes.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapesimport java.awt.*;import javax.swing.*;/** ... * The instantiable main class of the program. */class Ch5DrawShape {... public void start( ) { DrawableShape shape1 = getShape(); canvas.addShape(shape1); canvas.setMovement(DrawingBoard.SMOOTH); canvas.setVisible(true); canvas.start(); }©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapesprivate DrawableShape getShape( ) { int type = inputShapeType(); Dimension dim = inputDimension(); Point centerPt = inputCenterPoint(); DrawableShape shape = new DrawableShape(type, dim, centerPt); return shape;}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapesprivate int inputShapeType( ) { String str = JOptionPane.showInputDialog(null, "Selection: Enter the Shape number\n" + " 1 - Ellipse \n" + " 2 - Rectangle \n" + " 3 - Rounded Rectangle \n" ); int selection = Integer.parseInt(str); int type; switch (selection) { case 1: type = DrawableShape.ELLIPSE; break; case 2: type = DrawableShape.RECTANGLE; break; ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapes case 3: type = DrawableShape.ROUNDED_RECTANGLE; break; default: type = DrawableShape.ELLIPSE; break; } return type;}private Dimension inputDimension( ) { String str = JOptionPane.showInputDialog(null, "Enter the width of the shape\n" + " between 100 and 500 inclusive"); int width = Integer.parseInt(str); if (width 500) { width = 100; }©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapes str = JOptionPane.showInputDialog(null, "Enter the height of the shape\n" + " between 100 and 500 inclusive"); int height = Integer.parseInt(str); if (height 500) { height = 100; } return new Dimension(width, height);}private Point inputCenterPoint( ) { String str = JOptionPane.showInputDialog(null, "Enter the x value of the center point\n" + " between 200 and 800 inclusive"); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapes int x = Integer.parseInt(str); if (x 800) { x = 200; } str = JOptionPane.showInputDialog(null, "Enter the y value of the center point\n" + “ between 100 and 500 inclusive"); int y = Integer.parseInt(str); if (y 500) { y = 100; } return new Point(x, y); }...}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing ShapesThe DrawableShape class is now modified toimport java.awt.*;/**... * A class whose instances know how to draw themselves.*/class DrawableShape {public static final int ELLIPSE = 0;public static final int RECTANGLE = 1;public static final int ROUNDED_RECTANGLE = 2;private static final Dimension DEFAULT_DIMENSION = new Dimension(200, 200);©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapesprivate static final Point DEFAULT_CENTER_PT = new Point(350, 350);private Point centerPoint;private Dimension dimension;private int type;public DrawableShape( ) { this(ELLIPSE, DEFAULT_DIMENSION, DEFAULT_CENTER_PT);}public DrawableShape(int sType, Dimension sDim, Point sCenter) { type = sType; dimension = sDim; centerPoint = sCenter;}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapespublic void draw(Graphics g) { g.setColor(Color.blue); drawShape(g);}...public void setType(int shapeType) { type = shapeType;}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapesprivate void drawShape(Graphics g) { switch (type) { case ELLIPSE: g.fillOval(centerPoint.x - dimension.width/2, centerPoint.y - dimension.height/2, dimension.width, dimension.height); break; case RECTANGLE: g.fillRect(centerPoint.x - dimension.width/2, centerPoint.y - dimension.height/2, dimension.width, dimension.height); break; ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapescase ROUNDED_RECTANGLE: g.fillRoundRect(centerPoint.x - dimension.width/2, centerPoint.y - dimension.height/2, dimension.width, dimension.height, (int) (dimension.width * 0.3), (int) (dimension.height * 0.3)); break; } }}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing ShapesStep 4 Development: Allow the User to Select a ColorAdopt the same input style for accepting the shape in Step 3.Add a method named inputColor to the Ch5DrawShape class.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapesimport java.awt.*;import javax.swing.*;/** * Chapter 5 Sample Development: Color selection (Step 4) * * The instantiable main class of the program. */class Ch5DrawShape {... public void start( ) { DrawableShape shape1 = getShape(); shape1.setColor(inputColor()); canvas.addShape(shape1);©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapes canvas.setMovement(DrawingBoard.SMOOTH); canvas.setVisible(true); canvas.start(); } ... private Color inputColor( ) { String str = JOptionPane.showInputDialog(null, "Selection: Enter the Color number\n" + " 1 - Red \n" + " 2 - Green \n" + " 3 - Blue \n" + " 4 - Yellow \n" + " 5 - Magenta \n" ); int selection = Integer.parseInt(str); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing ShapesColor color; switch (selection) { case 1: color = Color.red; break; case 2: color = Color.green; break; case 3: color = Color.blue; break; case 4: color = Color.yellow; break; case 5: color = Color.magenta; break; ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapes default: color = Color.red; break; } return color;}...}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing ShapesThe DrawableShape class is now modified toimport java.awt.*;/** * Step 4: Adds the color choice * * A class whose instances know how to draw themselves. **/class DrawableShape {...private static final Color DEFAULT_COLOR = Color.blue; ... private Color fillColor;©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapespublic DrawableShape(int sType, Dimension sDim, Point sCenter) { type = sType; dimension = sDim; centerPoint = sCenter; fillColor = DEFAULT_COLOR; }public void draw(Graphics g) { g.setColor(fillColor); drawShape(g); }...public void setColor(Color color) { fillColor = color; }...}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing ShapesStep 5 Development: Allow the user to select a motion type. Adopt the same design as used in Steps 3 and 4 for the motion selection.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapesimport java.awt.*;import javax.swing.*;/** * Chapter 5 Sample Development: Color selection (Step 5) * * The instantiable main class of the program. */class Ch5DrawShape {... public void start( ) { DrawableShape shape1 = getShape(); shape1.setColor(inputColor()); canvas.addShape(shape1); canvas.setMovement(inputMotionType()); canvas.setVisible(true); canvas.start(); }...©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing Shapes private int inputMotionType( ) { String str = JOptionPane.showInputDialog(null, "Selection: Enter the Motion number\n" + " 1 - Stationary (no movement) \n" + " 2 - Random Movement\n" + " 3 - Smooth Movement \n" ); int selection = Integer.parseInt(str); int type; switch (selection) { case 1: type = DrawingBoard.STATIONARY; break; case 2: type = DrawingBoard.RANDOM; break; case 3: type = DrawingBoard.SMOOTH; break; default: type = DrawingBoard.SMOOTH; break; } return type; } ...}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing ShapesNo changes are required for the DrawableShape class, as the DrawingBoard class is the one responsible for shape movement.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.5.7 Sample Development: Drawing ShapesStep 6 Development: FinalizePerform a critical program review, looking for unfinished methods, inconsistency or error in the methods, missing comments, etc.Make extensions to the program if desired.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Các file đính kèm theo tài liệu này:

  • pptchap_5_1976.ppt