Chapter 6 - Decisions - PowerPoint PPT Presentation

About This Presentation
Title:

Chapter 6 - Decisions

Description:

... learn how to compare integers, floating-point ... Comparisons ... 'Hello' comes before 'car' Comparisons == tests for identity, equals() for identical content ... – PowerPoint PPT presentation

Number of Views:21
Avg rating:3.0/5.0
Slides: 81
Provided by: david603
Category:

less

Transcript and Presenter's Notes

Title: Chapter 6 - Decisions


1
Chapter 6 - Decisions
2
Chapter Goals
  • To be able to implement decisions using if
    statements
  • To understand how to group statements into blocks
  • To learn how to compare integers, floating-point
    numbers, strings, and objects
  • To recognize the correct ordering of decisions in
    multiple branches
  • To program conditions using boolean operators and
    variables

3
Decisions
  • So far, our examples havent made any decisions
  • The same code gets executed no matter what
  • Assignment 1
  • Path
  • BankAccount
  • This is called sequential execution
  • Is this how real applications work?

4
Decisions
  • The real world requires decisions
  • Is it time to feed the cat? Can a book be
    checked out?
  • Essential feature of nontrivial programs is to
    make decisions based on input
  • The answers to these decision require different
    actions
  • Introduces the need for control statements

5
If statements
  • Conditional statements are represented with
    if-then-else statements
  • Scanner stdin new Scanner(System.in)
  • int testScore stdin.nextInt()
  • if (testScore lt 70)
  • System.out.println(You are below the mean)
  • else
  • System.out.println(You are above the mean)

6
If Statements Syntax
  • if (ltboolean expressiongt)
  • ltthen blockgt
  • else
  • ltelse blockgt

7
Example
  • withdraw() method we implemented allowed user to
    withdraw as much money as they wanted
  • Is this realistic?
  • What decision should withdraw() make?
  • What should the decision be based on?

8
Example
  • public void withdraw(double amount)
  • if (amount lt balance)
  • balance - amount

9
(No Transcript)
10
Example
  • Most banks also charge an overdraft penalty, how
    would we go about changing our example to
    implement this?

11
(No Transcript)
12
Statements
  • The decision we made only resulted in one
    instruction whichever way we took
  • Most decisions lead to a sequence of instructions
    (multiple statements).
  • In order to show that the entire sequence of
    instructions belong to the then-block (or
    else-block), we group them with curly braces
  • A sequence of instructions surrounded by curly
    braces is called a block

13
Example
  • if (amount lt balance)
  • System.out.println(Legal Withdrawal)
  • balance balance amount
  • else
  • balance balance OVERDRAFT_PENALTY

14
Statements
  • Block statement a group of statements enclosed
    within curly braces
  • Methods
  • Classes
  • if statements, switch statements, loops
  • Simple statement
  • Basic statement such as balance balance
    amount
  • Compound statement
  • Statements that have multiple paths of execution
  • If statements, loops

15
If Statements
  • If you have a single statement, not required
  • if (testScore lt 70)
  • System.out.println(You are below the mean)
  • else
  • System.out.println(You are above the mean)
  • But convention to use them anyways
  • Helpful for adding temporary output to check if a
    branch is executed
  • Makes nested if-else statements easier to read

16
If Statements Syntax
  • if(condition) statement
  • if (condition) statement1
  • else statement2
  • statement must be a statement - simple, compound,
    or block

17
Style
  • Use indentation to indicate nesting levels
  • public class BankAccount
  • public void withdraw()
  • if (amount lt balance)
  • balance - amount

18
Die Example
  • // Declare and create Die objects
  • Die die1 new Die()
  • Die die2 new Die()
  • // Roll die objects
  • die1.roll() die2.roll()
  • // Save results in new variables
  • int roll1 die1.getTop()
  • int roll2 die2.getTop()

19
Die Example
  • // Test for doubles
  • if ( roll1 roll2 )
  • System.out.println( "Doubles" )
  • // rest of program

20
Die Example
roll1 roll2
true
System.out.println( doubles! )
false
... continue with rest of program
21
Die Example
  • // Test for doubles
  • if ( roll1 roll2 )
  • System.out.println( "Doubles" )
  • else
  • System.out.println(
  • "Sorry, no doubles" )
  • // rest of program

22
Die Example
roll1 roll2
true
System.out.println( doubles! )
false
System.out.println( sorry ... )
... continue with rest of program
23
Selection Operator
  • Selection Operator
  • condition ? value1 value2
  • If the condition is true, value1 is returned.
  • If the condition is false, value2 is returned.
  • Example Absolute Value
  • y (x gt 0) ? x -x

24
Booleans
  • boolean is a primitive data type that holds one
    of two values
  • true
  • false
  • Any time a decision needs to be made, we make
    that decision using a boolean expression, which
    evaluates to a boolean value
  • Note a mathematical expression returns a
    numerical value

25
Boolean Expressions
  • What operators are used for boolean expressions?
  • lt less than
  • lt less than or equal to
  • gt greater than
  • gt greater than or equal to
  • equal to
  • ! not equal to

26
Boolean Expressions
  • Boolean expressions are just like mathematical
    expressions, but they return true or false (not
    int, double, etc)
  • Examples
  • 3 8 lt 5 5
  • 6 4 gt 0
  • testScore lt 80
  • testScore 2 gt 350

27
If Statements
  • When the computer reaches an if statement, it
    first evaluates the boolean expression
  • If that expression is true, the ltthen blockgt is
    executed
  • Otherwise, the ltelse blockgt is executed
  • An if statement is called a branching statement
    because it branches to a block of code

28
Comparisons
  • Comparing whole numbers is trivial
  • int a 5
  • if (a 5)
  • System.out.println(Wow this is easy!)
  • else
  • System.out.println(Java really sucks)

29
Comparisons
  • Comparing real numbers is more difficult because
    we have to take into account roundoff errors.
  • double r Math.sqrt(2)
  • double d r r 2
  • if (d ! 0)
  • System.out.println(Your equation is incorrect,
    the result is d)
  • Your equation is incorrect, the result is
    4.440892098500626E-16

30
Comparisons
  • This is a problem, since logically the equation
    makes sense
  • Lesson Floating point numbers may not be exact
  • Solution Use range of values that are close
    enough
  • Should be close to 0

31
Comparisons
  • To avoid roundoff errors, don't use or ! to
    compare floating-point numbers
  • To compare floating-point numbers test whether
    they are close enough x - y e
  • final double EPSILON 1E-14if (Math.abs(x -
    y) lt EPSILON)// x is approximately equal to y
  • e is a small number such as 10-14

32
Comparisons
  • We can do comparisons with characters as well
  • They work according to ASCII values
  • char choice 'Q'
  • if (choice lt 'Z') System.out.println("valid"
    ) else
  • System.out.println("invalid")
  • What is the output?

33
Side Note Characters
  • Remember that we said a char is one letter,
    digit, or symbol that the computer thinks of as a
    number.
  • We can cast chars to int and vice versa
  • Examples
  • (int) 'D' -gt 68
  • (char) 106 -gt 'j'
  • (char) ('D' 1) -gt 'E'

34
Comparisons
  • Boolean operators can be used on objects, but do
    they mean the same thing?
  • They probably dont do what you expect
  • Primitive types vs. reference types (objects)
  • To test two Strings, use equals() method

35
String Comparisons
  • Don't use for strings!if (input "Y") //
    WRONG!!!
  • Use equals methodif (input.equals("Y"))
  • string1.equals(string2)
  • tests references, .equals() tests contents

36
String Comparisons
  • String s1 "Robby", s2
  • s2 s1

37
String Comparisons
  • What is the result of
  • s1 s2

Why?
38
String Comparisons
  • String s1 "Robby", s2
  • s2 "Robby"

39
String Comparisons
  • What is the result of
  • str1 str2

Why?
40
String Comparisons
  • String s1 "Robby", s2
  • s2 new String( s1 )

41
String Comparisons
  • What is the result of
  • s1 s2

Why?
42
String Comparisons
  • What is the result of
  • s1.equals(s2)

Why?
43
String Comparisons
  • equalsIgnoreCase can be used to compare strings
    while ignoring case
  • Case insensitive test ("Y" or "y")if
    (input.equalsIgnoreCase("Y"))
  • string1.equalsIgnoreCase(string2) // returns
    boolean
  • compareTo returns a number that tells which
    string comes before the other in the dictionary
  • 0 indicates that the strings are the same

44
String Comparisons
  • string1.compareTo(string2)
  • Returns lt 0 if string1 comes first
  • Returns 0 if they are equal
  • Returns gt 1 if string2 comes first
  • Example "car" comes before "cargo"
  • All uppercase letters come before lowercase
    "Hello" comes before "car"

45
Comparisons
  • tests for identity, equals() for identical
    content
  • Most classes have an equals() method defined
  • Rectangle box1 new Rectangle(5, 10, 20, 30)
  • Rectangle box2 box1
  • Rectangle box3 new Rectangle(5, 10, 20, 30)
  • box1 box3 is false
  • box1.equals(box3)is true
  • box1 box2 is true
  • Note equals() must be defined for the class for
    this to work

46
(No Transcript)
47
Null
  • Reference variables store a reference (address)
    for an actual object
  • What do they store when they havent been set to
    refer to an object?
  • null is a Java reserved word to designate that no
    object has been set for that variable

48
Null
  • Can be used in tests
  • if (middleInitial null)System.out.println(firs
    tName " " lastName)
  • elseSystem.out.println(firstName " "
    middleInitial ". " lastName)
  • Use , not equals, to test for null
  • null is not the same as the empty string ""

49
Multiple Alternatives
  • if (score gt 90)
  • System.out.println("Great!")
  • else if (score gt 80)
  • System.out.println("Good")
  • else if (testScore gt 70)
  • System.out.println("OK")
  • else if (testScore gt 60)
  • System.out.println("Passing")
  • else if (testScore gt 50)
  • System.out.println("Hmm...")
  • else if (testScore gt 0)
  • System.out.println("Study!")
  • else
  • System.out.println("Invalid Score")

50
Multiple alternatives
  • First condition that is true is the ONLY
    statement executed
  • Therefore, order matters
  • if (testScore gt 90)
  • System.out.println(Great!)
  • else if (testScore gt 80)
  • System.out.println(Good)
  • else if (testScore gt 70)
  • System.out.println(OK)

51
Multiple Alternatives
  • Wrong order here causes problems!
  • if (testScore gt 0)
  • System.out.println(Study!)
  • else if (testScore gt 50)
  • System.out.println(Hmm...)
  • else if (testScore gt 60)
  • System.out.println(Passing)

52
Multiple Alternatives
  • if (testScore gt 90)
  • System.out.println(Great!)
  • if (testScore gt 70)
  • System.out.println(OK)
  • if (testScore gt 50)
  • System.out.println(Hmm...)
  • These aren't exclusive statements anymore
  • Else matters!!!

53
Switch Statements
  • switch ( ltvariable namegt )
  • ltcase label 1gt ltcase body 1gt
  • ...
  • ltcase label ngt ltcase body ngt
  • Can only be used on integers, characters, or
    enumerated constants
  • Good for testing multiple values for one
    expression

54
Switch Statements
55
Switch Statements
  • 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.

56
(No Transcript)
57
Switch Statements
  • switch( c )
  • case y System.out.println(Yes)
  • break
  • case n System.out.println(No)
  • break
  • default System.out.println(Invalid
    entry)

58
Nested Decisions
  • then and else blocks can contain as many
    statements as needed
  • These blocks can also have another if statement
  • An if statement inside of another if statement is
    called a nested-if statement

59
Nested Decisions
  • if (testScore gt 70)
  • if (studentAge lt 10)
  • System.out.println(You did a great job)
  • else
  • System.out.println(You did pass)
  • //test score gt70 and age gt10
  • else //test score lt 70
  • System.out.println(You did not pass)

60
Tax Schedule Example
61
Tax Schedule Example
  • Compute taxes due, given filing status and income
    figure
  • branch on the filing status
  • for each filing status, branch on income level
  • The two-level decision process is reflected in
    two levels of if statements
  • We say that the income test is nested inside the
    test for filing status

62
(No Transcript)
63
  • if (status SINGLE)
  • if (income lt SINGLE_BRACKET1)
  • tax RATE1 income
  • else if (income lt SINGLE_BRACKET2)
  • tax RATE1 SINGLE_BRACKET1
  • RATE2 (income - SINGLE_BRACKET1)
  • else
  • tax RATE1 SINGLE_BRACKET1
  • RATE2 (SINGLE_BRACKET2 -SINGLE_BRACKET1)
  • RATE3 (income - SINGLE_BRACKET2)

64
  • else
  • if (income lt MARRIED_BRACKET1)
  • tax RATE1 income
  • else if (income lt MARRIED_BRACKET2)
  • tax RATE1 MARRIED_BRACKET1
  • RATE2 (income - MARRIED_BRACKET1)
  • else
  • tax RATE1 MARRIED_BRACKET1
  • RATE2 (MARRIED_BRACKET2 - MARRIED_BRACKET1)
  • RATE3 (income - MARRIED_BRACKET2)

65
Dangling Else
  • There is a good reason we always use curly braces
    in our programs
  • Very common error can be made
  • if (testScore gt60)
  • if(testScore lt 80)
  • System.out.println(You are in safe range)
  • else // Pitfall!
  • System.out.println(You may be in trouble)

66
Dangling Else
  • Which if statement does the else apply to?
  • Always the closest unclosed if
  • if (testScore gt60)
  • if(testScore lt 80)
  • System.out.println(You are in safe range)
  • else
  • System.out.println(You may be in trouble)

67
Using Boolean Expressions
  • Recall that the last primitive that we really
    haven't said much about is the boolean data type
  • double temp 100
  • boolean isHot temp gt 60
  • System.out.println(Is it hot? Ans isHot)

68
Predicate Methods
  • A predicate method returns a boolean valuepublic
    boolean isOverdrawn()   return balance lt 0
  • Use to test conditions just like another other
    method
  • if (harrysChecking.isOverdrawn()) . . .

69
Predicate Methods
  • Many predicate methods
  • String class equals()
  • Character class isUpperCase(), isDigit(),
    isLetter(), isLetter(), isLowerCase()
  • All of these are public static methods
  • Convention is to prefix "is" or "has"
  • Much like accessors use get and mutators use
    set

70
Example
  • Scanner class has a hasNextInt() method which
    allows you to test if there is an int before you
    get it (and cause program to crash)
  • Scanner in new Scanner(System.in)
  • int score
  • System.out.println(Enter Score)
  • if(in.hasNextInt())
  • score in.nextInt()

71
Boolean Operators
  • What if we want one expression to test multiple
    conditions?
  • Example Does a student have a score above 50
    and below 75?
  • Need boolean operators

72
Boolean Operators
  • Can use a logical operator to test simultaneously
  • AND true if both are true, false
    otherwise
  • OR true if either is true, false
    otherwise
  • ! NOT true of the expression is false,
  • false if it is true

73
Boolean Operators
74
Boolean Operators
  • Example
  • if (testScore gt 50 testScore lt 75)
  • System.out.println(In range C to D range)
  • Example
  • char c
  • if (!(c !))
  • System.out.print(c)

75
  • Many ways to write one expression
  • if (age lt 0)
  • System.out.print(valid)
  • else
  • System.out.print(invalid)
  • -------------------------------------
  • if (!(age gt 0))
  • System.out.print(valid)
  • else
  • System.out.print(invalid)
  • ----------------------------------
  • if (age gt 0)
  • System.out.print(invalid)
  • else
  • System.out.print(valid)

76
Order of Operations
  • Like before, boolean operators are evaluated left
    to right
  • Example Suppose y has the value 0
  • x / y gt z y 0 // Run time error, divide by
    // zero
  • y 0 x / y gt z // Legal

77
Precedence Table
Precedence Group Operator Associativity
9 subexpression ( ) inner to outer left to right
8 unary ! - right to left
7 multiplicative / left to right
6 additive - left to right
5 relational lt lt gt gt left to right
4 equality ! left to right
3 AND left to right
2 OR left to right
1 assignment right to left
78
Example
  • In math, we represent the range of x as
  • 80 x lt 90
  • How do we represent this as a boolean expression?
    (Be careful)

79
Boolean Expressions
  • Check validity of data
  • Divide by zero, out or range errors
  • Classify data
  • Test above mean, below mean
  • Flags
  • Store system settings or user preferences
  • Long messages, noise off, debug mode

80
Style
  • Equivalent statements given a boolean isRaining
  • if (isRaining true)
  • if (isRaining) //Preferred
  • Use good identifier names
  • isMoving vs. motionStatus
  • isCheckedOut vs. bookStatus
  • MOST COMMON ERROR!
  • if (x 5)
Write a Comment
User Comments (0)
About PowerShow.com