Chapter 5 - People Server at UNCW
Download
Report
Transcript Chapter 5 - People Server at UNCW
Chapter 5
Selection Statements
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 5 Objectives
After you have read and studied this
chapter, you should be able to
• Implement 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 to
• Nest 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 Statement
Statements in programs are executed in
sequence. We can add decisionmaking 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 Statement
The if statement is one type of selection
statement.
InputHandler input = new InputHandler();
int testScore = input.getInteger(“Enter
test score:”);
if (testScore < 70)
JOptionPane.showMessageDialog(“You did
not pass”);
else
JOptionPane.showMessageDialog(“You did
pass”);
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
5.1 The if Statement
The if statement specifies which block
of code to execute, depending on the
result of evaluating a test condition
called a boolean expression.
if (<boolean expression>)
<then block>
else
<else block>
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
5.1 The if Statement
The <boolean expression> is a
conditional expression that is
evaluated to either true or false.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 5.1
Mapping of the sample if statement to
the general format.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
5.1 The if Statement
The six relational operators we can use
in conditional expressions are:
<
<=
==
!=
>
>=
less than
less than or equal to
equal to
not equal to
greater than
greater than or equal to
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 5.2
The diagram showing the control flow of
the sample if statement.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
5.1 The if Statement
The 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.3
The 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 Variables
A boolean operator takes boolean
values as its operands and returns a
boolean value.
The three boolean operators are
• and:
&&
• or:
||
• not
!
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
5.2 Boolean Expressions and Variables
Boolean operators and their meanings:
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
5.2 Boolean Expressions and Variables
The 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 < x;
done = true;
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
5.3 Nested-if Statements
An if statement that contains another if
statements in either its then or else block
is called a nested-if statement.
if (testScore >= 70){
if (studentAge < 10){
System.out.println(“You did a great job”);
} else {
System.out.println(“You did pass”);
//test score >=70 and age >=10
}
} else { //test score < 70
System.out.println(“You did not pass”);
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 5.4
A diagram showing the control flow of
the example nested-if statement.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
5.4 Comparing Objects
When two variables are compared, we
are comparing their contents.
In the case of objects, the content is the
address where the object is stored.
The best approach for comparing
objects is to define comparison
methods for the class.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 5.5
How the equality == testing works with
the objects.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
5.4 Comparing Objects
Class Ch5Weight{
...
public boolean equals(Ch5Weight wgt) {
boolean result;
double thisGram = this.getGram();
double otherGram = wgt.getGram();
if (thisGram == otherGram){
result = true;
} else {
result = false;
}
return result;
}
...
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
5.5 The switch Statement
The switch statement provides an
efficient way to evaluate and process
multiple options.
switch (gradeLevel){
case 1: System.out.println(“Go
gymnasium”);
break;
case 2: System.out.println(“Go
Auditorium”);
break;
case 3: System.out.println(“Go
Hall Room 104”);
break;
case 4: System.out.println(“Go
Room 101”);
break;
}
to the
to the Science
to Halligan
to Root Hall
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 5.6
Mapping of the sample switch statement
to the general format.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
5.5 The switch Statement
The syntax for the switch statement is
switch ( < arithmetic
expression>){
<case label 1>: <case body 1>
...
<case label n>: <case body n>
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
5.5 The switch Statement
The data type of <arithmetic
expression> must be char, byte,
short, or int.
The value of <arithmetic
expression> is compared against the
constant i of <case label i>.
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 Statement
The 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.7
A 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 Statement
It 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 Graphics
We introduce four standard classes
related to drawing geometric shapes
on a window:
• java.awt.Graphics
• java.awt.Color
• java.awt.Point
• java.awt.Dimension
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
5.6 Drawing Graphics
We 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.8
How the position of the rectangle is
determined by the drawRect method.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 5.9
The distinction between the draw and fill
methods.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
5.6 Drawing Graphics
The 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 Graphics
There are public class constants
defined in the Color class for common
colors:
•
•
•
•
•
Color.black
Color.blue
Color.green
Color.magenta
Color.orange
and so on.
g.setColor(Color.blue);
g.drawRect(50, 50, 100, 30);
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 5.10
A frame with a white background
content pane and two colored squares.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
5.6 Drawing Graphics
A 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 Graphics
The 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.11
Bounding rectangles of various shapes.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
5.7 Sample Development:
Drawing Shapes
Write 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.12
Two 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 Shapes
Program flow:
1. Get the shape the user wants to
draw.
2. Get the color of the chosen shape.
3. Get the type of movement the user
wants to use.
4. Start the drawing.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
5.7 Sample Development:
Drawing Shapes
Program implementation:
1. Start with a program skeleton.
Explore the DrawingBoard class.
2. Define an experimental
DrawableShape class that draws a
dummy shape.
3. 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 Shapes
4. Add code to allow the user to specify
the color. Extend the
DrawableShape and other classes
as necessary.
5. Add code to allow the user to specify
the motion type. Extend the
DrawableShape and other classes
as necessary.
6. Finalize the code by tying up loose
ends.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Fig. 5.13
The program diagram for the
Ch5DrawShape program.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
5.7 Sample Development:
Drawing Shapes
Step 1 Development: Program Skeleton
• Use 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 Shapes
public 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 Shapes
Step 2 Development: Draw a Shape
Define 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 Shapes
import 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 Shapes
public 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 Shapes
The 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 Shapes
Step 3 Development: Allow the User to
Select a Shape
• Use 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 Shapes
import 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 Shapes
private 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 Shapes
private 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 < 100 || 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 < 100 || 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 < 200 || 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 < 100 || y > 500) {
y = 100;
}
return new Point(x, y);
}
...
}
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
5.7 Sample Development:
Drawing Shapes
The DrawableShape class is now
modified to
import 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 Shapes
private 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 Shapes
public 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 Shapes
private 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 Shapes
case 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 Shapes
Step 4 Development: Allow the User to
Select a Color
• Adopt 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 Shapes
import 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 Shapes
Color 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 Shapes
The DrawableShape class is now
modified to
import 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 Shapes
public DrawableShape(int sType, Dimension sDim,
Point sCenter) {
type
dimension
centerPoint
fillColor
=
=
=
=
sType;
sDim;
sCenter;
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 Shapes
Step 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 Shapes
import 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 Shapes
No 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 Shapes
Step 6 Development: Finalize
• Perform 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.