Chapter 3 Part a Basic Selection Structure

advertisement
***** SWTJC STEM *****
•
Program Structure
Structure refers to how the internal parts of programs are
put together.
• Software is “structured” by design rules that have
been adopted and used.
• Design rules make structured programs . . .
 Easy to write and read
 Easy to debug (find mistakes and errors)
 Easy to understand
 Easy to modify
 Easy to reuse
Chapter 5 cg 49
***** SWTJC STEM *****
•
Program Structure cont.
Program Structure (cont.)
• No one wants an expensive, flashy sports car that
stalls in traffic because of poor design.
• No one wants a program with a trendy, colorful
Windows interface that suddenly crashes with the
infamous “blue screen of death”.
Chapter 5 cg 49
***** SWTJC STEM *****
Flow of Control
Three Control Structures
Flow of control is the order in which program statements
execute within a method.
1.Sequence
 Allows you to create a step-by-step process.
2.Selection (Decision Making)
 Allows you to choose which action to take .
3.Repetition (Loops)
 Allows you to execute an action many times.
These three structures constitute all that is needed to
program any algorithm!
Chapter 5 cg 50
***** SWTJC STEM *****
Flow of Control
Sequence Structure
Entry Point
Step 1
Step 2
Step 3
Step 4
Exit Point
Unless otherwise directed, programs proceed in a step
by step manner. Note there is one entry point and one
exit point.
Chapter 5 cg 51
***** SWTJC STEM *****
Sequence Structure
With a Method Execution
Entry Point
Entry Point
Step 1
Step 1
Step 2
Step 2
Method
Step 3
Step 3
Step 4
Step 4
Exit Point
Exit Point
At step 2 the method is invoked. After completion,
execution returns to the next step (step 3 in this case).
Chapter 5 cg 51
***** SWTJC STEM *****
Flow of Control
Selection Construct Choices
1. One-way selection - Use simple if.
2. Two-way selection - Use if - else.
3. Multi-way selection - Use either:
1. Differing conditions - Use if - else if - else if - .... - else.
2. Same variable or expression with multiple choices - Use
switch.
Chapter 5 cg 52
***** SWTJC STEM *****
•
•
•
•
Flow of Control
With a Selection Structure
Selection structure is handled using a selection statement.
In Java, there are four selection statement constructs:
• if condition . . .
• if condition . . . else
• if condition . . . else if . . . else if . . .else
• switch . . . case 1condition . . . case 2 condition . . . default
In each case, the condition is based on a Boolean expression that
evaluates to either true or false.
Boolean expressions contain Boolean variables, literals (true and
false), Boolean relational operators, and logical operators.
Chapter 5 cg 52-53
***** SWTJC STEM *****
Boolean Relational Operators
Relational expressions compare numeric, char, and string
expressions taking the form
expression1 relational operator expression2
Example: (x + 2)
> y2
Relational Operator
Use
Returns true if
>
op1 > op2
op1 is greater than op2
>=
op1 >= op2
op1 is greater than or equal to op2
<
op1 < op2
op1 is less than op2
<=
op1 <= op2
op1 is less than or equal to op2
==
op1 == op2
op1 and op2 are equal
!=
op1 != op2
op1 and op2 are not equal
Chapter 5 cg 54
***** SWTJC STEM *****
•
•
•
Boolean Relational Examples
Note that the relational operator for equality is double equal
sign == as distinguished from the assignment operator that is a
single equal sign =.
Boolean variables hold Boolean values; i.e., true or false.
Examples:
•
boolean lightsOn = true;
Declares a Boolean variable lightsOn and assigns it the
value true.
•
int i = 10, j = 5;
boolean bValue = (i > j);
Boolean expression (i > j) evaluates to true ( i is greater
than j) then a true value is assigned to bValue.
Chapter 5 cg 54
***** SWTJC STEM *****
Boolean Relational Examples
Examples (cont.):
•
int i = 10, j = 12;
boolean bValue = (j - 3 > i);
Boolean expression (j - 3 > i) evaluates to false (9 is not
greater than 10), then a false value is assigned to bValue.*
•
int waterTempMax = 230, waterTemp = 240;
boolean tempAlarm = (waterTemp >= waterTempMax);
Boolean expression (waterTemp >= waterTempMax)
evaluates to true (waterTemp is greater than or equal to
waterTempMax), then a true is assigned to tempAlarm.
*Note: Relational operators are lower precedence than
numeric or character/string operators and are done last.
Chapter 5 cg 54
***** SWTJC STEM *****
One-Way Selection
Entry Point
In one-way selection, the simple if
statement appears as
if ( relational expression )
executable statement;
“Statement” is executed only if
“Decision” is true. Otherwise,
execution skips “Statement” and
passes to the “Exit Point”.
Decision false
true
Statement
Exit Point
Chapter 5 cg 55
***** SWTJC STEM *****
One-Way Selection Example
Entry Point
Consider this example:
“If a person is a minor (under 21
years of age), print the message
‘Youth is a wonderful thing. Enjoy
it!’. In any case, print the message,
‘Age is a state of mind.’.”
Age<21?
false
true
“Youth is . . .”
“Age is . . .”
Exit Point
Chapter 5 cg 55
***** SWTJC STEM *****
One-Way Selection Code
The Java code from AgeOneWay.java is
...
final int MINOR = 21;
int age = 18;
If true
if ( age < MINOR)
System.out.println(“Youth is a wonderful thing. Enjoy it!”);
System.out.println("Age is a state of mind.");
...
• Note that the executable part of the if statement is indented to
indicate it is governed by the if statement.
• The indentation is strictly for human readability! Only the first
executable line after the if is governed by the if. See the red
bracket above.
Chapter 5 cg 55
***** SWTJC STEM *****
In two-way selection, the if-else
statement permits execution of
different statements for true and
false. It appears as
if ( relational expression )
executable statement - true;
else
executable statement-false;
“Step 2T” is executed only if
“Decision” is true, while “Step 2F”
is executed only if “Decision” is
false.
Two-Way Selection
Entry Point
Step 1
Decision false
true
Step 2T
Step 2F
Exit Point
Chapter 5 cg 56
***** SWTJC STEM *****
Two-Way Selection Example
Entry Point
Consider this example:
“If a person is a minor (under 21
years of age), print the message
‘Youth is a wonderful thing. Enjoy
it!’. If a person is not a minor,
print the message, “Too soon the
bird of youth flies the coop.” In
any case, print the message, ‘Age
is a state of mind.’.”
Age<21?
true
false
“Too soon . . .”
“Youth is . . .”
“Age is . . .”
Exit Point
Chapter 5 cg 56
***** SWTJC STEM *****
Two-Way Selection Code
From AgeTwoWay.java,
...
final int MINOR = 21;
int age = 18;
If true
if ( age < MINOR)
System.out.println(“Youth is a wonderful thing. Enjoy it!”);
else
System.out.println(“Too soon the bird of youth flies the coop!”);
System.out.println("Age is a state of mind.");
If false
...
Note that the executable part of the if and else statements are
single lines and indented for readability to indicate they are
governed by the if statement.
Chapter 5 cg 56
***** SWTJC STEM *****
When more than one statement
appears in an if-else structure use
braces { } to define a block. It
appears as
if ( relational expression ) {
executable statement 2t;
executable statement 3t;
...
}
else {
executable statement 2f;
executable statement 3f;
...
}
Multi-statement Selection
Entry Point
Step 1
Decision true
false
ex.st 2f
ex.st 2t
ex.st 3f
ex.st 3t
Exit Point
Chapter 5 cg 56
***** SWTJC STEM *****
Multi-Statement Example
Entry Point
Consider this problem:
num<100?
“A segment of code is used to
increment a variable named
num. However, when num
reaches 100, instead of
incrementing it is reset to zero.
An appropriate message is
output for each situation.”
true
false
num = 0
num = num +1
“num is reset”
“num is . . .”
Exit Point
Chapter 5 cg 56
***** SWTJC STEM *****
Multi-Statement Code
true block false block
A block is a sequence of statements delimited by a pair of braces
{ }. From Incr.java,
...
int num = 50;
if (num < 100) {
If true
++num;
System.out.println(“num is incremented to “ + num);
}
else {
num = 0;
System.out.println(“num is reset to “ + num);
}
If false
...
Chapter 5 cg 56
***** SWTJC STEM *****
Chapter 5 Part a
Nested if’s
A block can contain additional if-else statements, with additional
indented blocks. Such constructs are called nested if’s.
Next slide please.
Chapter 5 cg 59
***** SWTJC STEM *****
Nested if’s
Consider the problem:
“If the temperature is 80
degrees or greater and the
humidity is greater than 60%,
most people find it
uncomfortably warm. If the
temperature is greater than 80
degrees and the humidity is
60% or less, most people find it
warm, but not uncomfortable.
Temperatures below 80,
regardless of humidity, are
comfortable. Create a program
segment that represents this
situation.”
Entry Point
T<80?
true
false
Comfortable
true
H≤60?
false
Warm but
Uncomfortable
Warm and
uncomfortable
Nested if
Exit Point
Chapter 5 cg 59
Nested if
***** SWTJC STEM *****
Nested if’s
From AgeOneWay.java,
...
if (temperature < 80) {
return “T = “ + Int.toString( temperature) +
“, H= “ + Int.toString(humidity) +
“: It's comfortable.";
}
else {
if (humidity <= 60)
{
return “T = “ + Int.toString( temperature) +
“, H= “ + Int.toString(humidity) +
“: It's warm, but comfortable.";
}
else {
return “T = “ + Int.toString( temperature) +
“, H= “ + Int.toString(humidity) +
“: It's warm and uncomfortable!";
}
}
Chapter 5 cg 59
***** SWTJC STEM *****
Comfort Object (UML)
Class
Comfort
---------------------------------------------------temperature: int
Attributes
humidity: int
---------------------------------------------------setTemperature (int value): void
getTemperature ( ): int
setHumidity (double int): void
Methods
getHumidity ( ): int
isComfortable: boolean
toString( ): String
Unified Modeling Language (UML) Diagram.
Chapter 5 cg 59
***** SWTJC STEM *****
Declarations and Constructor
public class Comfort {
private int temperature, humidity;
public Comfort(int temperature, int humidity) {
this.temperature = temperature;
this.humidity = humidity;
}
Chapter 5 cg 59
***** SWTJC STEM *****
Attribute Setters and Getters
public void setTemperature(int temperature){
this.temperature = temperature;
}
public void setHumidity(int humidity) {
this.humidity = humidity;
}
public int getTemperature() {
return temperature;
}
public int getHumidity() {
return humidity;
}
Chapter 5 cg 59
***** SWTJC STEM *****
public boolean isComforatble( ) {
if (temperature < 80) {
return true;
}
else {
if (humidity <= 60) {
return true;
}
else {
return false;
}
}
}
isComfortable Check
T<80?
true
false
Comfortable
true
H≤60?
false
Warm but
Uncomfortable
Warm and
uncomfortable
Chapter 5 cg 59
***** SWTJC STEM *****
toString Method
public String toString () {
if (temperature < 80) {
return "T = " + Integer.toString(temperature) +
", H = " + Integer.toString(humidity) +
": It's comfortable.";
}
else {
if (humidity <= 60) {
return "T = " + Integer.toString(temperature) +
", H = " + Integer.toString(humidity) +
": It's warm, but comfortable.";
}
else {
return "T = " + Integer.toString(temperature) +
", H = " + Integer.toString(humidity) +
": It's warm and uncomfortable!";
}
}
}
Chapter 5 cg 59
Download