Decisions (chapter 3)

Download Report

Transcript Decisions (chapter 3)

Decision Structures
Michele Co
CS 101-E
Today
• if statements
• Logical expressions
– Truth tables
– Boolean algebra
– DeMorgan’s laws
• Boolean expressions
• Relational Operators
– Equality
– Ordering
• Expressions vs. Statements
UVa CS101E Spring 2007
2
Background
• So far, sequential code
• We need more control…
– Java constructs to control execution of
statements
• if
• if-else
• if-else-if
Relies on logical expressions
UVa CS101E Spring 2007
3
Conditional Statements
Conditional Constructs
• if statements
– if
– if-else
– if-else-if
• switch statements
UVa CS101E Spring 2007
5
Basic if statement
• Syntax
if (Expression)
Action
• If the Expression is true then
execute Action
• Action is either a single
statement or a group of
statements within braces
• For us, it will always be a
group of statements within
braces
UVa CS101E Spring 2007
Expression
true
false
Action
6
If semantics
Rearrange value1 and
value2 to put their
values in the proper
order
Are the numbers out
of order
value2 < value1
true
false
int rememberValue1 = value1
value1 = value2
value2 = rememberValue1
The numbers were rearranged into
the proper order
The numbers were initially in
order
The numbers are in order
UVa CS101E Spring 2007
7
What an if statement
executes
• An if statement executes the next block of
code
• A block is either:
– A single statement without curly brackets:
if (a == b)
System.out.println (“a==b!!!”);
– A number of statements enclosed by curly
brackets:
if (a == b) {
System.out.print (“a”);
System.out.print (“==”);
System.out.print (“b”);
System.out.println (“!!!”);
}
UVa CS101E Spring 2007
8
What is the Output?
int m = 5;
int n = 10;
if (m < n)
++m;
++n;
System.out.println(" m = " + m + "
n = “ + n);
UVa CS101E Spring 2007
9
Code Demo:
AverageScore.java
UVa CS101E Spring 2007
10
The if-else statement
• Syntax
if (Expression)
Action1
else
Action2
• If Expression is true then
execute Action1 otherwise
execute Action2
Expression
true
false
Action1
Action2
• The actions are either a single
statement or a list of
statements within braces
UVa CS101E Spring 2007
11
Finding the maximum of
two values
System.out.print("Enter an integer number: ");
int value1 = stdin.nextInt();
System.out.print("Enter another integer number: ");
int value2 = stdin.nextInt();
int maximum;
if (value1 < value2) {
// is value2 larger?
maximum = value2;
// yes: value2 is larger
}
else { // (value1 >= value2)
maximum = value1;
// no: value2 is not larger
}
System.out.println("The maximum of " + value1
+ " and " + value2 + " is " + maximum);
UVa CS101E Spring 2007
12
Finding the maximum of
two values
Is value2 larger than value1
Yes, it is . So value2 is
larger than value1. In
this case, maximum is
set to value2
value1 < value2
true
maximum = value2
No, its not. So value1
is at least as large as
value2. In this case,
maximum is set to
value1
false
maximum = value1
Either case, maximum is set
correctly
UVa CS101E Spring 2007
13
Code Demo: Division.java
UVa CS101E Spring 2007
14
If-then-else precedence
if (number != 0)
if (number > 0)
Which if does this
else refer to?
System.out.println("positive");
else
System.out.println("negative");
UVa CS101E Spring 2007
15
Code Demo: TestResults.java
UVa CS101E Spring 2007
16
Logical Expressions
Logical Expressions
• The branch of mathematics dealing
with logical expressions is Boolean
algebra
– Developed by the British mathematician
George Boole
• Logical expression values
– logical true
– logical false
UVa CS101E Spring 2007
18
Logical Operators
• Logical and
– &&
• Logical or
– ||
• Logical not
–!
UVa CS101E Spring 2007
19
Truth Tables
• Formal specification for an operator
• Lists all combinations of operand
values and results for each
combination
UVa CS101E Spring 2007
20
Logical AND (&&)
p
q
False
False
True
True
False
True
False
True
p and q
False
False
False
True
Short circuit evaluation for logical AND:
if left hand side is false, then whole
expression evaluates to false
UVa CS101E Spring 2007
21
Logical OR (||)
p
q
False
False
True
True
False
True
False
True
p or q
False
True
True
True
Short circuit evaluation for logical OR:
if left hand side is true, then whole
expression evaluates to true
UVa CS101E Spring 2007
22
Logical NOT (!)
p
False
True
UVa CS101E Spring 2007
not p
True
False
23
Boolean Algebra
• Complex logical expressions can be
formed by combining simpler logical
expressions
p
q
p and q
not (p and q)
False
False
True
True
False
True
False
True
False
False
False
True
True
True
True
False
UVa CS101E Spring 2007
24
DeMorgan’s Laws (1)
• not (p and q) equals (not p) or (not
q)
p
False
False
True
True
q
False
True
False
True
UVa CS101E Spring 2007
p and q
False
False
False
True
not (p and q) ( not p)
True
True
True
False
(not p) or
(not q)
(not q)
True
True
True
False
False True
False False
True
True
True
False
25
DeMorgan’s Laws (2)
• not (p or q) equals (not p) and (not
q)
p
False
False
True
True
q
False
True
False
True
UVa CS101E Spring 2007
p or q
not (p or q)
False
True
True
True
True
False
False
False
(not p) and
( not p) (not q)
(not q)
True
True
False
False
True
False
True
False
True
False
False
False
26
DeMorgan’s Laws
• ! (a && b) == (! a) || (! b)
• ! (a || b) == (! a) && (! b)
UVa CS101E Spring 2007
27
Sidewalk chalk guy
• Source:
http://www.gprime.net/images/sidewalkchalkg
uy/
UVa CS101E Spring 2007
28
Boolean Expressions
Java’s boolean type
• Has 2 literal constants
– true
– false
• Operators
– &&
– ||
–!
UVa CS101E Spring 2007
30
Defining boolean variables
• Local boolean variables are uninitialized
by default
boolean isWhitespace;
boolean receivedAcknowledgement = true;
boolean haveFoundMissingLink = false;
isWhitespace
receivedAcknowledgement
haveFoundMissingLink
UVa CS101E Spring 2007
true
false
31
Assignment vs. comparison
• = is the assignment operator
– Consider:
int x;
x = 5;
• == is the comparison operator
– Consider:
int x = 5;
System.out.println (x == 5);
System.out.println (x == 6);
– Prints out true, false
UVa CS101E Spring 2007
32
Equality Operators
• ==
– returns true if operands have the same
value
• !=
– returns true if operands have different
values
Works with all sorts of values
UVa CS101E Spring 2007
33
Evaluating boolean
expressions
• Suppose
boolean
boolean
boolean
boolean
p = true;
q = false;
r = true;
s = false;
• What is the value of
p
!s
q
p && r
q || s
UVa CS101E Spring 2007
p && s
p == q
q != r
r == s
q != s
34
Evaluating boolean
expressions
• Suppose
int i = 1;
int j = 2;
int k = 2;
char c = '#';
char d = '%';
char e = '#';
• What is the value of
j == k
i == j
c == e
c == d
UVa CS101E Spring 2007
i != k
j != k
d != e
c != e
35
A bit of humor…
UVa CS101E Spring 2007
36
Ordering operators
• Java provides ordering operators for
the primitive types
– <, >, <=, and >=
– They correspond to mathematical
operators of <, >, ≤, and ≥
• Together the equality and ordering
operators are known as the
relational operators
UVa CS101E Spring 2007
37
Relational Operators Summary
Relational Operator
Meaning
>
is greater than
<
is less than
>=
is greater than or equal to
<=
is less than or equal to
==
is equal to
!=
is not equal to
UVa CS101E Spring 2007
38
Evaluating Boolean
Expressions
Evaluation boolean
expressions
• Suppose
int i = 1;
int j = 2;
int k = 2;
• What is the value of
i<j
j<k
i <= k
j >= k
i >= k
UVa CS101E Spring 2007
40
Unicode values
• Character comparisons are based on their Unicode
values
• Characters ‘0’, ‘1’, … ‘9’ have expected order
– Character ‘0’ has the encoding 48
– Character ‘1’ has the encoding 49, and so on.
• Upper case Latin letters ‘A’, ‘B’, … ‘Z’ have expected
order
– Character ‘A’ has the encoding 65, character ‘B’ has
the encoding 66, and so on.
• Lower case Latin letters ‘a’, ‘b’, … ‘z’ have expected
order
– Character ‘a’ has the encoding 97, `b’ 98,
etc.
UVa CS101E Spring 2007
41
Evaluation boolean
expressions
• Suppose
char c = '2';
char d = '3';
char e = '2';
• What is the value of
c
c
c
d
c
< d
< e
<= e
>= e
>= e
UVa CS101E Spring 2007
42
Operator precedence
revisited
• Highest to lowest
– Parentheses ()
– Unary operators – Multiplicative operators * / %
– Additive operators + – Relational ordering <,>, <=, >=
– Relational equality ==, !=
– Logical and &&
– Logical or ||
– Assignment =
UVa CS101E Spring 2007
43
Expressions vs. Statements
• Statement
– Single command for Java to execute
– Examples
• System.out.println (“hello world”);
• int x = 4;
• ++x;
• Expression
– Returns a value (does not have semi-colon)
• Note the difference between the following:
– ++i
– ++i;
UVa CS101E Spring 2007
is an expression
is a statement
44
Sand Castles
UVa CS101E Spring 2007
45
Evaluating Boolean
Expressions
Precedence
In-Class Exercise
More Complex Boolean
Expressions w/Precedence
1.
2.
3.
4.
5.
6.
7.
7
3
4
7
2
2
6
<4<1
- -4 != 6 % 11
< 9 == false
> 2 != false
== 2 == 1
–6<6–2
% 5 <= 5 + 7
UVa CS101E Spring 2007
47
What Order of Evaluation?
What Result?
1.
2.
3.
4.
5.
6.
7.
8.
9.
3 < 7 && 7 < 14
2 > 6 && 6 == 14
false || false && true
4 == 6 || 6 != 4
true || false && true && false
! ( 4 != 8 != true)
! false || ! true
8 / 3 >= 1 == ! true
false || true && true || false
UVa CS101E Spring 2007
48
Expressions and Floating
Point Precision
FloatTest.java
Take care with floating-point
values
• Consider
double a = 1;
double b = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1
+ 0.1 + 0.1 + 0.1 + 0.1
double c = .9999999999999999;
• Two true expressions!
c == b
b != a
• Two false expressions!
a == b
b != c
• Problem lies with the finite precision of the floating-point
types
• Instead with the ordering operators for closeness
UVa CS101E Spring 2007
51
How to solve this
• Don’t compare floating-point values if you can
help it!
– Both doubles and floats
• Need to test if the two doubles are “close” in
value
final double EPSILON = 0.000001;
boolean foo = Math.abs (a-b) < EPSILON;
UVa CS101E Spring 2007
52
UVa CS101E Spring 2007
53
Debugging
Debugging
• Webster’s English Dictionary
1. to remove insects from
2. to eliminate errors in or
malfunctions of <debug a
computer program>
3. to remove concealed microphone or
wiretapping device
UVa CS101E Spring 2007
55
Basic Debugging Process
1.
2.
3.
4.
5.
Recognize that a bug exists
Isolate the source of the bug
Identify the cause of the bug
Determine a fix for the bug
Apply the fix and test it
– if a problem still exists, re-evaluate
assumptions, go back to start
UVa CS101E Spring 2007
56
Step 1: Recognizing the Bug
• Check
– the format and content of data are correct
– if unanticipated data values are given
– if values are corrupted or handled incorrectly
• The more minor the error, the MORE
difficult to locate!!!
• Questions
– What conditions cause the problem?
– Are there workarounds?
UVa CS101E Spring 2007
57
Step 2: Isolate the Sources of
the Bug
1. Is the input correct?
2. Is it read in properly?
3. Is it processed correctly?
1. Step through the program sequentially
2. Hypothesize where the problem might be
3. ... may have to iterate until sources are found
UVa CS101E Spring 2007
58
Step 3: Determine the Cause
of the Bug
• Is the data wrong? If so, why?
• Was the data handled incorrectly?
– Why?
• Misunderstanding of/lack of familiarity with
the system?
• Logic error?
• Unexpected values? (Values outside of
unstated assumptions)
• Does this error occur in other
sections of the code?
UVa CS101E Spring 2007
59
Step 4: Determine a Fix
• Need knowledge of the system
• May expose other hidden bugs
– Possible large design flaws
UVa CS101E Spring 2007
60
Step 5: Fix and Test (Repeat,
as necessary)
• Apply the fix
• Check to see that the fix addresses
the problem
– Has the original problem been fixed?
– Are there any new problems? (Unusual
side effects?)
Large systems use regression tests (test suite)
UVa CS101E Spring 2007
61
Making Debugging More
Efficient
1.
2.
3.
4.
5.
6.
•
•
•
•
•
Recognize that you might not fully understand the
assumptions or system (and that this is ok...)
Start debugging early
As you write your code, insert checks
•
Brainstorm possible ways for bugs to occur
Suspect user input
Add code to carefully check inputs
Develop a set of tests to exercise the code
Change only ONE thing at a time!
Back out changes that have no effect
Problem isn’t where originally thought
That area of code isn’t being reached, so isn’t part of the
bug at hand
May introduce new bugs after current bug is fixed
UVa CS101E Spring 2007
62
In-Class Debugging
Exercises
Debugging Decisions
ifError1.java, ifError2.java,
ifError3.java, switchError.java
Switch and if-else-if
• if-else-if structures that handle
integral data can be converted to
switch statements
• ifToSwitchConversion.java
UVa CS101E Spring 2007
64