Download ch04

Document related concepts
no text concepts found
Transcript
Intro to Programming
& Algorithm Design
Decisions
Decisions
Decisions
Assg
This presentation can be viewed on line in a file named:
ch04.IntrotoProg.ppt
Copyright 2003 by Janson Industries
1
Objectives
n
Explain
u
Boolean expressions
u
Comparison operators
u
If/Then/Else logic
u
AND and OR logic
u
Nested Ifs
u
Case structure
2
Copyright 2014 by Janson Industries
Decision Structure
n
Up till now all instructions in a
module executed in sequence
u
n
Decision structures allow
programmer to define the specific
condition(s) when a statement
should be executed
u
Copyright 2014 by Janson Industries
i.e. Statements executed in order
from top to bottom
Conditions specified as Boolean
expressions
3
Boolean Expression
n
Results in a value of true or false
n
Most basic consists of
u
u
u
n
Constant Value or Variable
Comparison Operator
Constant Value or Variable
Examples
u
u
gender = "F"
hoursWorked > 40
4
Copyright 2014 by Janson Industries
Boolean Expression
n
Values in expression can be a
variables or constants
u
In both examples, the first value
was a variable and the second
was a constant
F
n
But it doesn't have to be that way
Most languages support the
following comparison operations
u
u
Equal, Not Equal
Greater Than, Less Than
5
Copyright 2014 by Janson Industries
Boolean Expression
n
In addition you can combine
equal, greater than, and less
than to form
u
u
n
Different languages support
comparison operations with
different commands
u
u
Copyright 2014 by Janson Industries
Greater Than or Equal
Less Than or Equal
u
.equals
EQ
equal
6
Boolean Expression
Most support the algebraic symbols
> - greater than
< - less than
>= - greater than or equal to
<= - less than or equal to
Equal and Not Equal are a little
tricky
A = 10 in many languages, assigns the
value 10 to the variable A
A == 10 compares variable A to the
constant value 10
Copyright 2014 by Janson Industries
7
Boolean Expression
Not Equal often expressed as
<> - not equal
However Java, and the various
versions of C use !=
Exclamation point means not
Examples
state != "FL"
isPrint = !true
!(salary > 75000)
8
Copyright 2014 by Janson Industries
Boolean Expression
Negative logic can be confusing
Try not to use
For instance, instead of
if (!(salary > 75000))
Use
if (salary <= 75000)
Often, in programming languages,
the Boolean expression is enclosed
in ()
Copyright 2014 by Janson Industries
9
Boolean Expression
However sometimes the nonnegative logic is not viable
For instance, the alternative to
state != "FL"
Would be 49 conditions, which
would be much more code and
therefore
Less efficient
More likely to have errors
Copyright 2014 by Janson Industries
10
Boolean Expression
Can perform same selection
with different operators
If (price > limit) Then
finalCost = price * luxuryTax
Else
finalCost = price * salesTax
Endif
If (price <= limit) Then
finalCost = price * salesTax
Else
finalCost = price * luxuryTax
Endif
11
Copyright 2014 by Janson Industries
Boolean Expression
Which one is better?
The one that is more efficient
The one that causes the fewer number
of statements to be executed
How determine?
Need to know business/data
Are more than 50% of the prices over
or under the limit?
• If over limit, check price > limit first
• If under limit, check price <= limit first
12
Copyright 2014 by Janson Industries
Boolean Expression Gotcha
Must compare values of the
same type
Bad expressions:
totalCost == "Joe Smith"
TotalCost is a numeric variable
gender > 10
Gender is a string variable
10 == "A"
Comparing a number to a string
13
Copyright 2014 by Janson Industries
Decision Structure
In pseudocode, use the word If
followed by a Boolean condition in
parenthesis
Statements to be executed if true
follow Then and are indented
If (month == 1) Then
Display “Jan”
End If
If (month == 2) Then
Display “Feb”
Copyright 2014 by Janson Industries
End If
14
Boolean Expression
month
== 1
False
month
== 2
False
True
Display “Jan”
True
In flow charts, put
into diamond
symbol (selection)
Two logic paths
out of diamond
True
Display “Feb”
Copyright 2014 by Janson Industries
False
15
Java if Statement
Syntax of an if/else statement
if(boolean expression) { statements to
be executed if true }
if (month == 1) {
System.out.println(“Jan”);
}
if (month == 2) {
System.out.println(“Feb”);
}
16
Copyright 2014 by Janson Industries
Java if Statement
When comparing a String variable
must use .equals
String gender;
:
:
if (gender.equals(“f”)) {
System.out.println(“Female”);
}
if (gender.equals(“m”)) {
System.out.println(“Male”);
}
17
Copyright 2014 by Janson Industries
Dual Alternative Decision
Can specify what should happen if
condition is false
In pseudocode, use the word Else
and indent statements to be
executed if false
If (gender == “F”) Then
Display “Female”
Else
Display “Male”
End If
18
Copyright 2014 by Janson Industries
Dual Alternative Decision
Have false leg come out the left
side of the diamond
False
Display “Male"
gender
==
“F"
True
Display “Female"
19
Copyright 2014 by Janson Industries
Java if/else Statement
if(boolean expression) { statements to
be executed if true } else { statements
to be executed if false }
String gender;
:
:
if (gender.equals(“f”)) {
System.out.println(“Female”);
}
else{
System.out.println(“Male”);
}
20
Copyright 2014 by Janson Industries
Nested IFs
Having a decision structure
inside a decision structure
Allows checking for multiple
conditions
For example, insurance
company assigns risk rating
based on the type and color of
car
21
Copyright 2014 by Janson Industries
Nested IFs
If (isCarType == "Sports") Then
If (isCarColor == "Red") Then
insType = "HighRisk"
Else
insType = "Normal"
End If
Else
insType = "Normal"
End If
22
Copyright 2014 by Janson Industries
Nested IFs
False
insType="Normal"
True
isCarType
==
"Sports"
False
insType="Normal"
Copyright 2014 by Janson Industries
isCarColor
== "Red"
True
insType="HighRisk"
23
Java Nested ifs
Placing an if statement as one of
the statements to be executed in an
if/else clause
if (month == 1) {
System.out.println(“Jan”);}
Nested if
else {if (month == 2) {
System.out.println(“Feb”);}
else { if (month == 3) {
System.out.println(“Mar”);}
else { if (month == 4) {………
24
Copyright 2014 by Janson Industries
Case Structure
A large number of nested IFs can
be difficult to understand/debug
The Case structure is an
alternative
Use the keyword Select to
identify the variable to be
checked
Then the keyword Case followed
by the value to check for
25
Copyright 2014 by Janson Industries
Case Structure
Select month
Case 1:
Display “Jan”
Case 2:
Display “Feb”
Case 3:
Display “Mar”
Etc. etc.
End Select
26
Copyright 2014 by Janson Industries
Case Structure
Can have a default case
Identifies what to do if none of the
checked values is true
Appears after all the Case
statements
Select month
Etc. etc.
Case 12:
Display “Dec”
Default:
Display month, “ is not a valid value”
End Select
27
Copyright 2014 by Janson Industries
Case Structure
lightColor
“Green”
Display
“Maintain speed"
Copyright 2014 by Janson Industries
“Yellow”
Display
“Punch it!"
“Red”
Display
“Stop”
28
SFC Case Structure
Copyright 2014 by Janson Industries
29
SFC Case Structure
Click on circle to right of the Case symbol, then Edit, Insert
Specify the value to search for, then click OK
Copyright 2014 by Janson Industries
30
SFC Case Structure
Click on True circle and insert statements to perform if true
Copyright 2014 by Janson Industries
31
SFC Case Structure
Keep inserting cases until finished
Of course, need to define lightColor and assign a value
Copyright 2014 by Janson Industries
32
SFC Case Structure
Copyright 2014 by Janson Industries
33
Flowgorithm Case Structure
Doesn’t have one,
must use nested IFs
34
Copyright 2014 by Janson Industries
Java Case Structure
Uses the keyword switch
Very similar to the pseudo code in
SFC
The variable being checked is in
parenthesis
Need break statements in each
case because once the condition
is true, all subsequent statements
are executed
35
Copyright 2014 by Janson Industries
Switch
If there were no breaks:
The label would be set to Dec
The “Not a valid month” message would
be displayed
switch (month) {
case 1: monthLabel.setText(“Jan”); break;
case 2: monthLabel.setText(“Feb”); break;
case 3: monthLabel.setText(“Mar”); break;
:
:
:
:
:
default: System.out.println(“Not a valid
month!”);
}
36
Copyright 2014 by Janson Industries
Compound Condition
Use AND or OR to connect many
conditions
Each AND & OR links two conditions
AND means both conditions must be
true
Replaces nested if
OR means either one or both
conditions must be true
Replaces multiple ifs
37
Copyright 2014 by Janson Industries
Compound Condition
So instead of nested if:
If (isCarType == "Sports") Then
If (isCarColor == "Red") Then
insType = "HighRisk"
Else
insType = "Normal"
Endif
Else
insType = "Normal"
Endif
If (isCarType == "Sports" AND isCarColor == "Red") Then
insType = "HighRisk"
Else
insType = "Normal"
Endif
Copyright 2014 by Janson Industries
38
Compound Condition
So instead of multiple ifs:
If (state == "WA") Then
salesTaxRate = 0
Endif
If (state == "NJ") Then
salesTaxRate = 0
Endif
If (state == "WA" OR state == "NJ") Then
salesTaxRate = 0
Endif
39
Copyright 2014 by Janson Industries
Compound Condition
If you specified the following
OR condition
flavor == "vanilla" OR flavor ==
"chocolate"
And the ice cream man handed
you a chocolate ice cream cone
Would the ice cream man have
satisfied the condition? YES
40
Copyright 2014 by Janson Industries
Compound Condition
If you specified the following
AND condition
flavor = ="vanilla" AND flavor ==
"chocolate"
And the ice cream man handed
you a chocolate ice cream cone
Would the ice cream man have
satisfied the condition? NO
41
Copyright 2014 by Janson Industries
Truth Table
Shows
2 conditions: x and y
Every possible combination of T
and F for x and y
AND and OR compound condition
Boolean value for each combination
Cond x
Cond y
x AND y
x OR y
True
True
True
True
True
False
False
True
False
True
False
True
False
False
False
False
42
Copyright 2014 by Janson Industries
Truth Table
Two conditions:
Cond x: flavor == “Vanilla”
Cond y: coneType == “Sugar”
flavor
coneType
x AND y
x OR y
Vanilla
Sugar
True
True
Vanilla
Waffle
False
True
Chocolate
Sugar
False
True
Chocolate
Waffle
False
False
43
Copyright 2014 by Janson Industries
Compound Condition Efficiency
Conditions checked from left to
right
Short circuit evaluation stops
checking in an
AND as soon as a false condition is
found
OR as soon as a true condition is
found
44
Copyright 2014 by Janson Industries
Compound Condition Efficiency
If the programming language
supports short circuit evaluation
Specify the conditions so that the
least amount of checks are
performed
The fewer the checks, the faster
the program will execute
45
Copyright 2014 by Janson Industries
OR Efficiency
Put the condition that is most likely
to be true first in an OR condition
For instance, if 30% of sales come
from NJ and only 5% from WA
If (state == "NJ" OR state == " WA") Then
salesTaxRate = 0
Endif
Means that only 70% of the time is
the 2nd condition checked
Alternative would result in 2nd condition
being checked 95% of the time
46
Copyright 2014 by Janson Industries
AND Efficiency
Put the condition that is most likely
to be false first in an AND condition
For instance, if 50% of customers
are female and 90% are over 21
If (gender == "F" AND age > 21) Then
admissionType = "Free"
Endif
Means that only 50% of the time is
the age checked
Alternative would result in gender
being checked 90% of the time
47
Copyright 2014 by Janson Industries
Compound Condition Mistakes
Most of the time specifying two
values for the same variable and
connecting them with an AND
carColor == "blue" AND carColor
== "red"
Means the condition can never
be true
How can the car color be both red
and blue?
48
Copyright 2014 by Janson Industries
Compound Condition
However checking a single
variable for two values with < or
> and an AND means you can
search for ranges
salary < 30000 AND salary >
20000
Means any salary from 20,001 to
29,999 would make the
expression true
49
Copyright 2014 by Janson Industries
Compound Condition
In Flowgorithm use AND and/or
OR in the diamond shape
50
Copyright 2014 by Janson Industries
Java uses && for AND, || for OR
(| is upper case \)
Here's the Java example of the compound AND condition
Prove by changing salary to 44000, compile, and run
51
Copyright 2014 by Janson Industries
Condition Mistakes
Be careful with > and <
If we selected students for the
dean's list with the following:
gpa > 3.5
It would be incorrect because
Students with gpa = 3.5 not
selected
Selection should be
gpa >= 3.5
52
Copyright 2014 by Janson Industries
Compound Condition Mistakes
Also,
salary > 30000 AND salary < 20000
No salary value can make this true
salary < 30000 OR salary > 20000
Every salary value will make this true
Another mistake, not specifying a
full condition
carColor = "blue" AND = "red"
Need the variable carColor in the
second condition
Copyright 2014 by Janson Industries
53
Compound Condition Mistakes
Unnecessary checks
If (salary >= 100000) Then
incomeTaxRate = .28
Else
If (salary < 100000 AND >= 60000) Then
incomeTaxRate = .25
End If
End If
No need to check if < 100000
a second time
Copyright 2014 by Janson Industries
54
Combining AND’s and OR’s
The AND is evaluated first (from
left to right) then the OR
So if there were a car with the
following characteristics
color = "red", price = 16000, style =
"sports"
And the condition was:
style = "sports" OR color = "red" AND price < 15000
It would be evaluated as follows:
55
Copyright 2014 by Janson Industries
Combining AND’s and OR’s
color = "red", price = 16000, style = "sports"
style = “sports” OR color = “red” AND price < 15000
style = “sports” OR True AND price < 15000
style = “sports” OR True AND False
style = “sports” OR False
True OR False
True
56
Copyright 2014 by Janson Industries
Combining AND’s and OR’s
AND forms a strong bond between conditions
If there were a file full of cars and we printed
only those cars that satisfied the condition:
style = "sports" OR color = "red" AND price < 15000
Would we get a list of:
Sports cars and cheap red cars
Or:
Cheap sports cars and cheap red cars
Copyright 2014 by Janson Industries
57
Combining AND’s and OR’s
AND forms a strong bond between conditions
style = "sports" OR color = "red" AND price < 15000
Means you will get a list of:
Sports cars and cheap red cars
Not:
Cheap sports cars and cheap red cars
style = "sports" OR color = "red" AND price < 15000
58
Copyright 2014 by Janson Industries
Combing AND’s and OR’s
To get a list of cheap sports cars and
cheap red cars could specify:
style = "sports" AND price < 15000
OR
color = "red" AND price < 15000
Or (if parentheses are supported)
(style = "sports" OR color = "red") AND price < 15000
59
Copyright 2014 by Janson Industries
Combining ANDs and ORs
Three ice cream variables
flavor, container, topping
Person says give me
Rocky Road AND Sugar Cone
OR Sprinkles OR Whip Cream
You hand over a
Dish filled with Sprinkles
Did you satisfy the condition?
Yes
Copyright 2014 by Janson Industries
60
Combining ANDs and ORs
Person says give me
Rocky Road AND Sugar Cone
OR Sprinkles OR Whip Cream
You hand over a
Rocky Road in a Dish
Did you satisfy the condition?
No
61
Copyright 2014 by Janson Industries
Combining ANDs and ORs
Person says give me
Rocky Road AND Sugar Cone
OR Sprinkles OR Whip Cream
You hand over a
Rocky Road in a Dish with
Whip Cream
Did you satisfy the condition?
Yes
62
Copyright 2014 by Janson Industries
New Condition Check
Java example of the compound
AND condition and inputting data
63
Copyright 2014 by Janson Industries
Run twice and check both true and false legs
64
Copyright 2014 by Janson Industries
Conditions
With many conditions, what to
do can get very complicated
Often flowchart or pseudocode
hard to read
Alternative is a Decision table
Copyright 2014 by Janson Industries
Shows conditions
Every possible combination of
conditional values
For each combination, what the
action(s) should be
65
Decision Table Example
All possible combinations
Conditions
Actions
Temp > 100
F
F
F
F
T
T
T
T
Nausea
F
F
T
T
F
F
T
T
Headache
F
T
F
T
F
T
F
T
Go to school
X
X
X
X
X
X
X
X
X
X
Go to doctor
Take aspirin
Take Pepto
X
X
X
X
X
X
X
Stay home
X
Actions to take based on
symptom combinations
Copyright 2014 by Janson Industries
66
Java example of the compound
AND condition and GUI
When run, dialog box pops up
Enter data, press OK
Problem: info read from dialog box is text. Have to convert to
numeric with the parseInt function
Copyright 2014 by Janson Industries
67
Dialog box disappears and results shown in command prompt
68
Copyright 2014 by Janson Industries
Compound Conditions Design Ex
Long distance charge basics:
Company charges 10 cents per
minute for all calls outside the
customer’s area code that last over
20 minutes
All other calls are 13 cents per
minute
Want to create a program to
calculate the cost of a phone call
69
Copyright 2014 by Janson Industries
Exercise
Further info about program:
Accepts data about one phone call from
user
Customer area code (three chars)
Customer phone number (eight chars)
Called area code (three chars)
Called number (eight chars)
Call time in minutes (four digits)
Displays:
All the inputted data
Price for the call.
70
Copyright 2014 by Janson Industries
Compound Conditions Design Ex
What's the algorithm for this
program?
Algorithm Answer
71
Copyright 2014 by Janson Industries
Compound Conditions Design Ex
Long distance charge basics:
Company charges 10 cents per
minute for all calls outside the
customer’s area code that last over
20 minutes
All other calls are 13 cents per minute
What variables would a program
need to handle this info?
I.e. What are the important pieces of
information?
Answer2
72
Copyright 2014 by Janson Industries
Exercise
Create command prompt external
design (XD) of this program
Answer2.5
Create a GUI external design (XD)
of this program
Answer2.6
73
Copyright 2014 by Janson Industries
Exercise
What is the pseudocode so far?
What is first command in pseudocode?
Where are variables defined?
How would you specify the variables?
Answer3
74
Copyright 2014 by Janson Industries
SFC Exercise
So in flow chart what is the first
symbol you enter?
Rectangle
What is text in rectangle?
Answer4
75
Copyright 2014 by Janson Industries
Exercise
After variables defined what's first
thing that has to happen
Read data in
What flow chart symbol?
Answer5
76
Copyright 2014 by Janson Industries
Exercise
Now what do we do?
Can we calculate price?
No, have to figure out type of call
What type of symbol is that?
Answer6
77
Copyright 2014 by Janson Industries
Exercise
Now we can calculate price
based on true or false
What type of symbol is that?
Answer7
78
Copyright 2014 by Janson Industries
Exercise
Now what?
Show the results
What type of symbol is that?
Answer8
Full pseudocode
Answer8.5
79
Copyright 2014 by Janson Industries
Java Exercise
In java, always initialize variables
Strings to null
String name = null;
Numbers to zero
int price = 0;
To make a variable value fixed
(unchangeable) define it as final
final double TAX_RATE = .065;
80
Copyright 2014 by Janson Industries
Java Exercise
In java, must create a lot of stuff
to read from command line
First, before the class header,
you must import the following
import java.io.*;
import java.util.Scanner;
public class ClassHeader {
81
Copyright 2014 by Janson Industries
Java Exercise
Then in the main method, create
the following variables and objects
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int numRead = 0;
Use the appropriate Scanner .next
function
Must assign read value to a
variable
numRead = keyboard.nextInt();
82
Copyright 2014 by Janson Industries
Java Exercise
Reads (.next(), nextInt(), etc.)
usually paired with a prompt
:
:
:
:
:
:
System.out.println(“Please enter qty of purchase”);
qty = keyboard.nextInt();
System.out.println(“Please enter item price”);
price = keyboard.nextDouble();
total = price * qty
System.out.println(“The transaction total is ” + total);
:
:
:
:
:
:
83
Copyright 2014 by Janson Industries
Java Exercise
Write the java program to
calculate the phone call cost and
implement the command line XD
Answer 9
84
Copyright 2014 by Janson Industries
Java Exercise
Modularize the java program to
calculate the phone call cost and
implement the command line XD
Answer 10
85
Copyright 2014 by Janson Industries
Comparing Strings
Some languages allow you to use
< and > to compare strings
Since all data stored as numbers
(0’s and 1’s), some letters greater
than others
A is less than B, B less than C, … Y
is less than Z, Z is less than a, a is
less than b, etc.
Java doesn’t allow <> with strings
86
Copyright 2014 by Janson Industries
Boolean Variables
Besides numeric and string
values there are Boolean values
Boolean values are true or false
There are also Boolean variables
that can hold a Boolean value
Can use a Boolean variable in a
condition instead of a Boolean
expression
87
Copyright 2014 by Janson Industries
Boolean Variables
Module main
Declare Integer hoursWorked
Declare Real payRate, salary
Declare Boolean isOvertime
Display “Enter number of hours worked ”
Input hoursWorked
If (hoursWorked > 40) Then
isOvertime = true
Else
isOvertime = false
End If
Display “Enter pay rate ”
Input payRate
If (isOvertime) Then
salary = hoursWorked * (payRate * 1.5)
Else
salary = hoursWorked * payRate
End If
Display “Salary is ”, salary
End Module
88
Copyright 2014 by Janson Industries
Points to Remember
Decisions/selections require Boolean
expressions or variables
Boolean expressions result in a value
of true or false
Use relational operator(s) to build
Boolean expression
Can create compound conditions by
combining Boolean expressions with
AND and/or OR operators
89
Copyright 2014 by Janson Industries
Assignments
Non-Graded
Chap 4 labs 3.1-3.4
Graded
Chap 4 lab 3.5
90
Copyright 2014 by Janson Industries