Control Structures - PowerPoint PPT Presentation

About This Presentation
Title:

Control Structures

Description:

See methods top of page 186 for method to handle this. Operands. Operands can be: Literals ... See example top page 200. Returning booleans from methods. Look ... – PowerPoint PPT presentation

Number of Views:238
Avg rating:3.0/5.0
Slides: 72
Provided by: Tho865
Category:

less

Transcript and Presenter's Notes

Title: Control Structures


1
Chapter 4
  • Control Structures
  • Decisions
  • Loops

2
Chapter 4 selection structures
  • This chapter begins a new path in our programming
    ability
  • Basically we can cause our programs to follow
    different paths, react differently to different
    situations.
  • Its an exciting time to be learning Java
    programming

3
Chapter Overview
  • Control structures
  • Boolean expressions
  • If statements
  • Nested if
  • Switch
  • Looping

4
Section 4.1 Control structures
  • Sequence
  • Selection
  • Alter normally sequential flow of a program
  • Repetition
  • Alter normally sequential flow of a program

5
Boolean Expressions
  • Boolean has two possible values
  • True
  • False
  • Simplest Boolean expression is variable
  • boolean leapYear true
  • Can only be assigned true or false

6
Relational operators
  • lt less than
  • lt less than or equal
  • equal
  • gt greater than
  • gt greater than or equal
  • ! not equal

7
Reading Boolean data
  • Use JOptionPane.showConfirmDialog(null, Is this
    fun?)
  • This is the result of the statement
  • Returns 0 for yes, 1 for no, 2 for cancel

8
Using the result
  • To convert this value to boolean simply use the
    result like this
  • boolean myBool (returnNum 0)
  • See methods top of page 186 for method to handle
    this

9
Operands
  • Operands can be
  • Literals
  • Variables

10
Boolean Operators
  • and
  • or
  • ! not

11
And
And 1 0
1 True False
0 False False
12
Or
Or 1 0
1 True True
0 True False
13
not
not Result
1 False
0 True
14
Boolean Operators
  • (salary lt minimumSalary) (dependents gt 5)
  • (temperature gt 90.0)
  • (humidity gt 0.90)

15
Boolean variables in expressions
  • winningRecord (!onProbation)

16
Boolean Assignment
  • variable expression
  • same true
  • same (x y)

17
Short-circuit
  • Short circuit evaluation
  • Stops evaluating as soon as knows the outcome.
  • Can cause problems depending on what is in
    statement

18
Writing Conditions
  • (min lt x) (x lt max)

x
min
max
19
Comparing Characters
  • c lt d true
  • a gt A true
  • 3 gt 4 false

20
Comparing Strings
  • Must use String methods
  • string1.equals(string2)

21
Lexicographic Comparison
  • string1.compareTo(string2)
  • Negative value if string 1 lt string 2
  • Value 0 if string 1 string 2
  • Positive value if string 1 gt string 2
  • See table pg 195

22
Section 4.3 if statement
  • if (gross gt 100.00)
  • net gross tax //if expression is true
  • else
  • net gross //if expression is false

true
false
23
One selection
  • if (x ! 0.0)
  • product product x

24
Syntax single selection
  • if (condition)
  • statement

25
Syntax 2 alternatives
  • if (condition)
  • statement
  • else
  • statement

26
Look at web example
  • http//faculty.juniata.edu/thomas/cs110/ifelse/Pag
    e1.htm

27
If and compound statements
  • Use the braces to create a block of code in the
    if statement.
  • if (x gt y)
  • temp x
  • x y
  • y temp
  • //end if

28
If else and compound
  • See example top page 200

29
Returning booleans from methods
  • Look at example 4.8 page 201
  • good way
  • need not do as shown on the bottom of the page

30
5.5 Decision steps in Algorithms
  • Decision step selects one of several actions.
  • Review example 4.13 Pages 204-205

31
Case Study page 205
  • Payroll problem
  • Analysis
  • Design
  • Implementation
  • Page 213 variable scope
  • Local
  • Data fields

32
4.5 nested ifs
  • Besides using the Boolean operators and !
    We can also create nested if statements.
  • Nested if statements are often more efficient
    than a sequence of if statements

33
Sequence versus Nested
  • if (x gt 0)
  • y y 1
  • if (x lt 0)
  • y y 1
  • if (x 0)
  • y y 2
  • if (xgt 0)
  • y y 1
  • else
  • if (x lt 0)
  • y y 1
  • else //btw x is 0
  • y y 2

34
Matching else with If
  • You must use indentiation to make it clear how
    your if/else match.
  • BUT!! The compiler ignores the white space
  • Java matches each else with its closest
    preceding if that is not already matched with an
    else

35
Good or Bad
  • if (x gt 0)
  • y y 4
  • if (x lt 0)
  • y y - 4
  • else
  • y y 4

36
Multiple alternative format
  • if (score gt 90)
  • displayResult(A)
  • else if (score gt 80)
  • displayResult(B)
  • else if (score gt 70)
  • displayResult(C)
  • .
  • .

37
Example
  • Order matters big time see page 220
  • Review tax example page 221

38
Tips
  • Code nested ifs one statement at a time.
  • Code outer if then the internal ifs
  • TEST TEST TEST

39
Switch statement
  • Switch allows you to select from several
    alternatives.
  • Works especially well when based on the value of
    one variable

40
This is what it looks like
  • switch (editOp)
  • case 0
  • search()
  • break
  • case 1
  • insert()
  • break
  • case 2
  • delete()
  • break
  • case 3
  • replace()
  • break
  • case 4
  • displayResult("All done")
  • break
  • default
  • displayResult("Invalid operation.")

41
Rules
  • The switch selector must be an ordinal data type.
  • Primitive
  • All values maybe listed
  • int, boolean, char
  • Not double
  • Break causes control to pass to statement after
    the switch.
  • Break statements are not always necessary

42
Another example
  • switch (month)
  • case 12 julian julian day
  • case 11 if (month 11)
  • julian julian day
  • else
  • julian julian 30
  • case 10 if (month 10)
  • julian julian day
  • else
  • julian julian 31
  • case 9 if (month 9)
  • julian julian day
  • else
  • julian julian 30
  • case 1 if (month 1)
  • julian julian day
  • else
  • julian julian 31
  • //end switch

Case 8 2 go in here, slides just arent big
enough
43
Returning a value
  • Use of a return in a switch case statement also
    stops execution of the statement.
  • I am a little fussy with entry level programmers
    having multiple exit points in a method, although
    will allow it in a switch statement.

44
Repetition Structures
  • In the programs we have written each line only
    executes at most 1 time.
  • There are times that we want statements to
    execute multiple times.
  • When would you want this?
  • Repetition is 3rd type of control structure
  • Sequence, selection, repetition

45
Overview
  • Loops
  • Counting loops
  • Sentinel controlled loops
  • Flag controlled loops
  • Menu driven loops
  • Loop types
  • while
  • for
  • do-while

46
Counting loops
  • Loop, repetition of steps in a program.
  • Counting loop repeats a predetermined number of
    times.
  • Name some real life examples of count controlled
    loops
  • Counter-controlled loops are controlled by a
    variable that keeps track of the number of
    repetitions performed.

47
While statement
  • Syntax
  • while (condition)
  • statement
  • Statement is the body of the loop
  • Can be compound
  • Condition, continues looping while condition
    remains true

48
Example
  • int countTenSum 1
  • int tenSum 0
  • while (countTenSum lt 11)
  • tenSum
  • tenSum countTenSum
  • countTenSum
  • countTenSum 1

49
Example
  • int numberEmp readInt(number of employees)
  • int countEmp 0
  • while (countEmp lt numberEmp)
  • //read pay data computer gross and net
  • //add one to counter
  • countEmp countEmp 1

50
Syntax and formatting
  • while (repetitionCondition)
  • loopBody
  • Must use indentation for clarity
  • As in other cases white space is totally ignored
    by compiler

51
Flow chart
countEmp lt numberEmp
Get Data Perform Calculations Increment counter
true
false
52
Loop-control variable
  • You must perform the following steps to your
    loop-control variable
  • Initialize
  • Test
  • Update
  • What is a loop that never ends called?
  • Can you sing the song that never ends?

53
For statement
  • This is used just for count controlled loops.
  • It is a special loop format that compresses count
    controlled into a special format.
  • Count control loops are used quite often.

54
While versus for
  • counter initial
  • While (counter lt final)
  • //loop processing
  • counter
  • for (counter initial
  • counter ltfinal
  • counter)
  • //loop processing

55
Syntax for statement
  • For (initialization statement
  • repetition condition
  • update statement)
  • loop body
  • Initialization statement occurs when for loop
    begins execution
  • Prior to each loop repetition (include 1st)
    condition tested
  • Update statement executes after each repetition

56
For examples
  • See code page 230 Example 4.18
  • (int i 10 i gt 0 i--)
  • System.out.println(i)
  • OK to create variable local in the loop

57
Accumulating a Sum
  • Loops can be used to accumulate a sum
  • Must have an accumulator
  • Loop causes accumulator to increase with each
    time loop is processed
  • This is a common use of a loop.
  • See page 231

58
New operators!!!
  • count count 1
  • count
  • accum accum count
  • accum count
  • countDown countDown 1
  • countDown--

59
Code
  • Review code on pages 234-236

60
State-controlled loops
  • Rather than loop for a specific number of
    repetitions (count control)
  • We can loop while a condition is true
  • Repetition stops when a particular state is
    reached. This state causes the loop-repetition
    condition to become false.
  • Can we always be sure these will end??

61
Code
  • See exams pages 240 - 241

62
4.8 Case Study
  • Problem
  • Write program to generate and solve arithmetic
    problems.
  • Has feature of varying difficulty
  • Checks answers and corrects when wrong

63
Analysis
  • Need class that generates math problems.
  • Problem represented by an operator and its left
    and right operands.
  • Operands generated randomly
  • Gets larger as difficulty increases
  • Called MathProblem

64
Analysis
  • Another class will use MathProblem to generate
    individual problems
  • Will also allow for looping and user interaction
  • Will additionally store statistics
  • Called MathDrill

65
Design
  • Table page 244
  • Table page 245

66
Implementation
  • See code pages 248 - 251

67
Section 4.9 Debugging and testing
  • Jbuilder includes a Debugger that allows user to
  • single-step through program
  • trace
  • set breakpoints
  • watch variables

68
Without debugger
  • Use diagnostic output statements
  • Put in println and showMessageDialog in
    appropriate places in program to monitor code and
    variables

69
4.10 Common Programming Errors
  • Fully parenthesis your boolean expressions also
  • boolean flag
  • flag x y //works but should be
  • flag (x y)

70
Other common errors
  • Watch use of versus
  • Watch use of and indentation
  • if (xy)
  • x 2
  • else
  • y 3
  • x 1
  • //continue code here

71
Other loop errors
  • Off by one
  • One to few
  • One to many
  • Check you loop boundaries
  • initial and final values of loop control
    variables are they right?
Write a Comment
User Comments (0)
About PowerShow.com