Chapter 3: Flow of Control Branching Statements - PowerPoint PPT Presentation

1 / 47
About This Presentation
Title:

Chapter 3: Flow of Control Branching Statements

Description:

The whole expression is true only when both of the smaller expressions are ... Software engineers often confronted with programming tasks where required action ... – PowerPoint PPT presentation

Number of Views:132
Avg rating:3.0/5.0
Slides: 48
Provided by: rober854
Category:

less

Transcript and Presenter's Notes

Title: Chapter 3: Flow of Control Branching Statements


1
Chapter 3 Flow of ControlBranching Statements
  • Dr. Hairong Zhao
  • hairong_at_calumet.purdue.edu
  • http//ems.calumet.purdue.edu/mcss/zhao
  • Purdue University Calumet

2
Review of Chapter 2 What Have You Learned?
  • Java primitive types (numbers, characters, etc.)
  • assignment statements and expressions
  • String
  • classes, methods, and objects
  • simple keyboard input and screen output

3
Chapter 3 Flow of Control
  • Flow of control is the order in which a program
    performs actions.
  • So far, all our programs are sequential they
    execute the same statements for every run of the
    program
  • public class MyIncome
  • public static void main(String args)
  • int monthlyPay, annualPay, expense, netIncome
  • monthlyPay 9999
  • expense 8888
  • annualPay monthlyPay 12
  • netIncome annualPay - expense
  • System.out.println(My monthly pay is "
    monthlyPay)
  • System.out.println(My annual pay is "
    annualPay)
  • System.out.println(My net income is "
    netIncome)

4
Chapter 3 Flow of Control
  • For general problem solving we need more
    capabilities
  • The ability to control which statements are
    executed
  • The ability to control how often a statement is
    executed
  • A branching statement chooses between two or more
    possible actions.
  • A loop statement repeats an action until a
    stopping condition occurs.

5
This Lecture
  • We will concentrate first on controlling which
    statements are executed
  • Java provides the if and switch conditional
    constructs to control whether a statement list is
    executed
  • The if constructs use boolean expressions to
    determine their course of action

6
This Lecture Branching Statements
  • Boolean expressions
  • The if Statement
  • if
  • if-else
  • if-else-if
  • The switch Statement
  • Conditional Operator

7
This Lecture Branching Statements
  • Boolean expressions
  • The if Statement
  • if
  • if-else
  • if-else-if
  • The switch Statement
  • Conditional Operator

8
Boolean expressions
  • A boolean expression has either the value true or
    false. It can be a
  • boolean variable
  • variables or expression connected by comparison
    operators
  • boolean variables or expressions connected by
    logical operators

9
Boolean expressions Comparison Operators
Note there is no space between the two
component operators of , !, gt, lt
10
Boolean expressions Logical Operators
  • not operator !
  • !(Boolean_Expression)
  • !(x lt 0)
  • and operator
  • (Sub_Expression_1) (Sub_Expression_2)
  • ((score gt 90) (grade lt 100))
  • Parentheses often are used to enhance
    readability.
  • The whole expression is true only when both of
    the smaller expressions are true.
  • or operator
  • (Sub_Expression_1) (Sub_Expression_2)
  • ((quantity gt 5) (cost lt 10))
  • The whole expression is true if at least one of
    the smaller expressions is true.

11
Boolean expressions Evaluation
  • Suppose
  • boolean p true
  • boolean q false
  • boolean r true
  • What is the value of
  • p q p q
  • !r p r
  • q ! r p r

12
Boolean expressions Evaluation
  • Suppose
  • int i 1
  • int j 2
  • int k 2
  • char c ''
  • char d ''
  • char e ''
  • What is the value of
  • j k i ! k
  • i lt j i lt k
  • c e d ! e

13
Boolean expressions Character comparisons
  • 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 letters A, B, Z have expected
    order
  • Character A has the encoding 65, character B
    has the encoding 66, and so on.
  • Lower case letters a, b, z have expected
    order
  • Character a has the encoding 97
  • Character b has the encoding 98, and so on.

14
Boolean expressions Evaluation
  • Suppose
  • char c '2'
  • char d '3'
  • char e '2'
  • What is the value of
  • c lt d
  • c lt e
  • c lt e
  • d gt e

15
Operator precedence revisited
  • Highest to lowest
  • Parentheses
  • Unary operators , -, , --, !
  • Multiplicative operators , /,
  • Additive operators -
  • Relational ordering lt, lt, gt, gt
  • Relational equality , !
  • Logical and
  • Logical or
  • Assignment

16
Branching Statements Outline
  • Boolean expressions
  • The if Statement
  • if
  • if-else
  • if-else-if
  • The switch Statement
  • Conditional Operator

17
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

can be any statement, in particular it can be
another if statement
18
Example
Is our number negative?
  • if (value lt 0)
  • value -value

value lt 0
true
false
value -value
Our number is now definitely nonnegative.
19
Why we always use braces
  • What is the output?
  • int m 5
  • int n 10
  • if (m lt n)
  • m
  • n
  • System.out.println(" m " m " n " n)
  • m 6 n 11

20
Example Sorting Two Values
  • // rearrange numbers if necessary
  • if (value2 lt value1)
  • // values are not in sorted order
  • int rememberValue1 value1
  • value1 value2
  • value2 rememberValue1
  • // display values
  • System.out.println("The numbers in sorted order
    are "
  • value1 " and then " value2)

21
Example Sort two values
22
This Lecture Branching Statements
  • Boolean expressions
  • The if Statement
  • if
  • if-else
  • if-else-if
  • The switch Statement
  • Conditional Operator

23
if-else Statement
  • Syntax
  • if (Expression)
  • Action1else Action2
  • If Expression is true then execute Action1,
  • otherwise execute Action2
  • The actions are either a single statement or a
    list of statements within braces

24
Example Finding the Maximum of Two Values
  • int maximum
  • if (value1 lt value2) // is value2 larger?
  • maximum value2 // yes value2 is larger
  • else // (value1 gt value2)
  • maximum value1 // no value2 is not
    larger
  • System.out.println("The maximum of " value1
  • " and " value2 " is " maximum)

25
Example Finding the Maximum of Two Values
26
Example Using for 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
  • if (a b)
  • System.out.println("a b")
  • else
  • System.out.println("a ! b")

27
Example Using for Floating-point Values
  • a ! b
  • 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
  • Problem lies with the finite precision of the
    floating-point types
  • Instead, test for closeness with floating-point
    values
  • Math.abs(a b) lt smallNumber

28
Example Using for objects
  • Consider
  • System.out.print("Enter a string ")
  • String s1 keyboard.next()
  • System.out.print("Enter another string ")
  • String s2 keyboard.next()
  • if (s1 s2)
  • System.out.println("Same")
  • else
  • System.out.println("Different")

29
Example Using for objects
  • When it is executed
  • System.out.print("Enter a string ")
  • String s1 keyboard.next()
  • System.out.print("Enter another string ")
  • String s2 keyboard.next()
  • Memory looks like
  • As a result no matter what is entered s1 and s2
    are not the same
  • They refer to different objects

30
Example Using for objects
  • Question how do we test the equality of two
    strings?

31
Using
  • is appropriate for determining if two integers
    or characters have the same value.
  • if (a 3)
  • where a is an integer type
  • is not appropriate for determining if two
    floating points values are equal. Use lt and
    some appropriate tolerance instead.
  • if (abs(a - b) lt epsilon)
  • where a, b, and epsilon are floating point types

32
Using , cont.
  • is not appropriate for determining if two
    objects have the same value.
  • To test the equality of objects of class String,
    use method equals, or equalsIgnoreCase
  • s1.equals(s2)
  • s2.equals(s1)
  • (Hello.equalsIgnoreCase(hello))

33
Example Compare Strings
  • Strings can be compared based on their
    lexicographic order
  • Lexicographic order is similar to alphabetical
    order, but is it based on the order of the
    characters in the ASCII (and Unicode) character
    set.
  • All the digits come before all the letters.
  • All the uppercase letters come before all the
    lower case letters.

34
Example Compare Strings
  • Strings comparison
  • lt, gt not allowed
  • using method compareTo
  • String_1.compareTo(String_2)
  • Method compareTo returns
  • a negative number if String_1 precedes String_2
  • zero if the two strings are equal
  • a positive number of String_2 precedes String_1.
  • String s1 Hello
  • String s2 hello
  • System.out.println(s1.compareTo(s2))

35
This Lecture Branching Statements
  • Boolean expressions
  • The if Statement
  • if
  • if-else
  • if-else-if
  • The switch Statement
  • Conditional Operator

36
If-else-if
  • Consider
  • if (number 0)
  • System.out.println("zero")
  • else
  • if (number gt 0)
  • System.out.println("positive")
  • else
  • System.out.println("negative")

37
If-else-if
  • Better
  • if (number 0)
  • System.out.println("zero")
  • else if (number gt 0)
  • System.out.println("positive")
  • else
  • System.out.println("negative")

Same results as previous segment but this
segment better expresses the meaning of what is
going on
38
Example Sorting Three Values
  • For sorting values n1, n2, and n3 there are six
    possible orderings
  • n1 n2 n3
  • n1 n3 n2
  • n2 n1 n3
  • n2 n3 n1
  • n3 n1 n2
  • n3 n2 n1
  • Suppose s1, s2, s3 are the sorted version of n1,
    n2, and n3

Try this yourself
39
This Lecture Branching Statements
  • Boolean expressions
  • The if Statement
  • if
  • if-else
  • if-else-if
  • The switch Statement
  • Conditional Operator

40
Switch statement
  • Software engineers often confronted with
    programming tasks where required action depends
    on the values of integer expressions
  • The if-else-if construct can be used
  • Separately compare the desired expression to a
    particular value
  • If the expression and value are equal, then
    perform the appropriate action
  • Because such programming tasks occur frequently
  • Java includes a switch statement
  • The task is often more readable with the switch
    then with the if-else-if
  • The switch statement is a mutltiway branch that
    makes a decision based on an integral (integer or
    character) expression.

41
Switch statement
42
The switch Statement, cont.
  • The action for each case typically ends with the
    word break.
  • The optional break statement prevents the
    consideration of other cases.
  • The switch expression can be anything that
    evaluates to an integral type.

43
Example Processing a request
  • Scanner keyboard new Scanner(System.in)
  • System.out.print("Enter a number ")
  • int n1 keyboard.nextInt()
  • System.out.print("Enter another number ")
  • int n2 keyboard.nextInt()
  • System.out.print("Enter desired operator ")
  • char operator keyboard.next().charAt(0)
  • switch (operator)
  • case '' System.out.println(n1 n2) break
  • case '-' System.out.println(n1 - n2) break
  • case '' System.out.println(n1 n2) break
  • case '/' System.out.println(n1 / n2) break
  • default System.out.println(Illegal request)

44
Example Testing for Vowel-ness
  • switch (ch)
  • case 'a'
  • case 'A'
  • case 'e'
  • case 'E'
  • case 'i'
  • case 'I'
  • case 'o'
  • case 'O'
  • case 'u'
  • case 'U' System.out.println("vowel)
  • break
  • default System.out.println("not a vowel)

Try to complete this as a program and run it
yourself!
The break causes an exiting of the switch
Default Handles all of the other cases
45
This Lecture Branching Statements
  • Boolean expressions
  • The if Statement
  • if
  • if-else
  • if-else-if
  • The switch Statement
  • Conditional Operator

46
The Conditional Operator
  • if (n1 gt n2)
  • max n1
  • else
  • max n2
  • can be written as
  • max (n1 gt n2) ? n1 n2
  • The ? and together are call the conditional
    operator or ternary operator.
  • Not recommended

47
The Conditional Operator, cont.
  • The conditional operator is useful with print and
    println statements.
  • System.out.print(You worked
  • ((hours gt 1) ? hours hour))
Write a Comment
User Comments (0)
About PowerShow.com