Decision Control Structures - PowerPoint PPT Presentation

1 / 27
About This Presentation
Title:

Decision Control Structures

Description:

Dangling Else. Nesting an if inside an if-else causes the dangling else problem: ... connect the else with the outer if thus avoiding the dangling-else problem ... – PowerPoint PPT presentation

Number of Views:30
Avg rating:3.0/5.0
Slides: 28
Provided by: drtimm8
Category:

less

Transcript and Presenter's Notes

Title: Decision Control Structures


1
Decision Control Structures
  • Dr. Tim Margush
  • University of Akron

2
Goals
  • Learn how to alter the flow of control using
    decision structures
  • Understand how comparisons of numbers, strings,
    and objects can be used in decision structures
  • Be able to use Boolean operators to create
    Boolean expressions

3
If
  • The basic decision structure is the if statement
  • To do, or not to do that is the question
  • Hamlet?
  • Used to execute or skip a statement or block of
    statements depending on a Boolean expression

4
Syntax of If
  • if (expression) statement
  • or
  • if (expression)
  • Statement list

true branch
agelt12?
false branch
price 0.75
Block Statement
5
If Else
  • The if statement allows an else clause
  • Two roads diverged in a yellow wood, and sorry I
    could not travel both and be one traveler
  • Frost
  • If-else is used to select between two
    alternatives
  • Choose exactly one of two execution paths

6
Syntax of If-Else
  • if (expression)
  • statement
  • else
  • statement
  • Either statement may be a block statement

true branch
false branch
student.isMale()?
student.reject()
student.accept()
7
Java Selection Operator
  • Java includes the selection operator
  • Syntax expression ? value1 value2
  • This evaluates to a single value
  • Result is value1 if expression is true
  • Result is value2 if expression is false
  • Notice that the result is an expression
  • max_xy xgty ? x y
  • In this example, the value returned by the
    selection operator becomes an operand of the
    assignment operator.

8
Comparisons
  • Relational operators
  • gt gt lt lt !
  • Be careful not to confuse with
  • Used to compare primitive data of the same type
  • Coercion allows comparisons between compatible
    types
  • Comparing objects (including strings) requires a
    method
  • Comparing object variables using the above
    operators actually compares their references, not
    the objects!

9
Comparing Floating Point Types
  • Warning! Data of type float and double are
    approximations of real numbers
  • float x10, y1if (y/x 0.1) y/x might not
    be exactly 0.1
  • Rewrite these comparisons as a difference being
    smaller than a threshold value
  • if (Math.abs( y/x 0.1) lt 1e-6)
  • The threshold value depends on the application
    (and the magnitude of the values)

10
Comparing Strings
  • Object comparisons require methods
  • if (aName.equals("Fred"))
  • True when the String aName has value "Fred"
  • Use .equalsIgnoreCase to disregard upper/lower
    case differences
  • if (description.compareTo("M")lt0)
  • True if String description has a value that
    starts with a letter coming before "M"
  • lt0 means less than, 0 means equal, gt0 means
    greater than
  • Use .compareToIgnoreCase if desired

11
Lexicographic Order
  • Lexicographic ordering
  • A "Computer Science"
  • B "Computing Concepts"
  • e comes before i so A lt B
  • Ordering of letters is based on the Unicode value
    for each character

12
Object References
  • String one "Fr""ed"
  • String two "Fred"
  • one two ?
  • one.equals(two) ?
  • one two
  • one two ?
  • Comparing object variables is simply comparing
    their references

one
two
Click to view animation steps
Animation Complete
13
null Object References
  • String x
  • This object variable has not been given a String
    object to point to yet is it initialized?
  • The null value is often used to indicate this
    situation
  • x null //no object yet
  • You may compare an object variable to null to
    determine if an object is referenced
  • if (x ! null) //do something with Object x

14
Options, Options, Options?
  • Choosing between two fundamentally different
    selection structures
  • Are the choices mutually exclusive or can more
    than one alternative occur?
  • "If I find fifty righteous people in the city of
    Sodom,
  • I will spare the whole place for their sake."
  • "If I find forty-five there," he said,
  • "I will not destroy it."
  • "What if only forty are found there?" He said,
  • "For the sake of forty, I will not do it."
  • "What if only thirty can be found there?" He
    answered,
  • "I will not do it if I find thirty there."
  • "What if only twenty can be found there?" He
    said,
  • "For the sake of twenty, I will not destroy it."
  • "What if only ten can be found there?" He
    answered,
  • "For the sake of ten, I will not destroy it."
  • -Genesis 18

15
Multiway Selection
  • Some/None of Many
  • if (condition1)
  • action1
  • if (condition2)
  • action2
  • if (condition3)
  • action3
  • A sequence of if statements
  • Exactly One of Many
  • if (condition1)
  • action1
  • else if (condition2)
  • action2
  • else if (condition3)
  • else
  • default_action
  • A single if statement

16
Sequence of If's
  • Exponential number of execution paths
  • n statements yields 2n possible paths
  • Use only when logic allows multiple actions to be
    processed

17
Nested If's
  • Linear number of execution paths
  • n nested statements yields n1 possible paths
  • Use when logic requires 1 action (or none) to be
    processed
  • Final else is optional

condition1?
action1
condition2?
action2
condition3?
action3
default_action
18
Dangling Else
  • Nesting an if inside an if-else causes the
    dangling else problem
  • if (condition1)
  • if (condition2)
  • action1
  • else
  • action2
  • Java follows this rule
  • Each else is matched with the closest unmatched
    if above it in the code
  • Thus the else matches with the nested if
    statement
  • The indentation is misleading as action 2 is
    executed only if condition1 is true and
    condition2 is false

if (condition1) if (condition2)
action1 else action2
Click to view animation steps
Animation Complete
19
Dangling Else
  • Avoiding the dangling else
  • if (condition1)
  • if (condition2)
  • action1
  • else
  • action2
  • Use a block statement to properly connect the
    else with the outer if thus avoiding the
    dangling-else problem

20
Multiway Selection via Switch
  • Useful when the decision is based on an integer
    value in a limited range
  • Notice the break statement
  • A break causes the flow of control to immediately
    exit the current block structure
  • switch (intValue)
  • case 2 statement break
  • case 5 statement break
  • case 9 statement break
  • default statement
  • Note cases can have more than one statement
    after the case label and before the break
    statement a block statement is not required.

21
Enumerated Types
  • Used to represent a limited range of discrete
    data
  • Rather than using integer codes such as 1, 2, 3
  • public class Person
  • public enum AgeGroup INFANT, CHILD, TEEN,
    ADULT
  • private AgeGroup ag null
  • public AgeGroup getAgeGroup return ag
  • //a client might use this as follows
  • if (p.getAgeGroup() Person.INFANT)

22
Boolean Expressions
  • Evaluate to a Boolean value
  • Boolean values are true or false
  • Example Boolean expressions
  • Predicate methods return a boolean value
  • name.equals("Fred")
  • Comparisons calculate a boolean result
  • 10 lt age

23
Boolean Operators
  • p and q
  • Written p q
  • True when both p and q are true
  • p or q
  • Written p q
  • True when at least one is true
  • not p
  • Written !p
  • True when p is false
  • Examples
  • agegt12 agelt20
  • Character.isDigit(x) x!'0'
  • name null name.equals("")
  • alt0 agt9
  • !fred.isHome()
  • !(alt4 bgt7)

24
Lazy Evaluation
  • Logical expressions involving a sequence of 's
    or 's are evaluated left to right
  • If the entire result can be determined before all
    of the sub-expressions are evaluated, then
    evaluation stops early
  • This is also called short circuit evaluation
  • agt0 alt9 short circuits to false if a is -3
  • alt0 agt9 short circuits to true if a is -3

25
Boolean Variables
  • Data type is boolean (lowercase b)
  • boolean done false
  • Store result of a boolean expression
  • done Character.isDigit(x)
  • done x0
  • Use without a comparison operator
  • if (done) not if (donetrue)
  • if (!done) not if (donefalse)

26
DeMorgan's Law
  • Negating 's results in 's
  • Negating 's results in 's
  • !(a xlt7) is the same as !a xgt7
  • !(xlt0 xgt9) is the same as !(xlt0) !(xgt9)
    which is also xgt0 xlt9

27
Summary
  • The basic decision structure in Java is specified
    using if and optionally else
  • The block statement is a group of statements that
    syntactically act as a single statement
  • Conditions control the flow of execution
  • Comparisons between primitive data (numbers,
    characters, and object references)
  • Comparisons between objects (via a method)
  • Boolean variables and expressions
Write a Comment
User Comments (0)
About PowerShow.com