Title: Control Structures
1Chapter 4
- Control Structures
- Decisions
- Loops
2Chapter 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
3Chapter Overview
- Control structures
- Boolean expressions
- If statements
- Nested if
- Switch
- Looping
4Section 4.1 Control structures
- Sequence
- Selection
- Alter normally sequential flow of a program
- Repetition
- Alter normally sequential flow of a program
5Boolean Expressions
- Boolean has two possible values
- True
- False
- Simplest Boolean expression is variable
- boolean leapYear true
- Can only be assigned true or false
6Relational operators
- lt less than
- lt less than or equal
- equal
- gt greater than
- gt greater than or equal
- ! not equal
7Reading 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
8Using 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
9Operands
- Operands can be
- Literals
- Variables
10Boolean Operators
11And
And 1 0
1 True False
0 False False
12Or
Or 1 0
1 True True
0 True False
13not
not Result
1 False
0 True
14Boolean Operators
- (salary lt minimumSalary) (dependents gt 5)
- (temperature gt 90.0)
- (humidity gt 0.90)
15Boolean variables in expressions
- winningRecord (!onProbation)
16Boolean Assignment
- variable expression
- same true
- same (x y)
17Short-circuit
- Short circuit evaluation
- Stops evaluating as soon as knows the outcome.
- Can cause problems depending on what is in
statement
18Writing Conditions
x
min
max
19Comparing Characters
- c lt d true
- a gt A true
- 3 gt 4 false
20Comparing Strings
- Must use String methods
- string1.equals(string2)
21Lexicographic 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
22Section 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
23One selection
- if (x ! 0.0)
- product product x
24Syntax single selection
25Syntax 2 alternatives
- if (condition)
- statement
- else
- statement
26Look at web example
- http//faculty.juniata.edu/thomas/cs110/ifelse/Pag
e1.htm
27If 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
28If else and compound
29Returning booleans from methods
- Look at example 4.8 page 201
- good way
- need not do as shown on the bottom of the page
305.5 Decision steps in Algorithms
- Decision step selects one of several actions.
- Review example 4.13 Pages 204-205
31Case Study page 205
- Payroll problem
- Analysis
- Design
- Implementation
- Page 213 variable scope
- Local
- Data fields
324.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
33Sequence 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
34Matching 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
35Good or Bad
- if (x gt 0)
- y y 4
- if (x lt 0)
- y y - 4
- else
- y y 4
36Multiple alternative format
- if (score gt 90)
- displayResult(A)
- else if (score gt 80)
- displayResult(B)
- else if (score gt 70)
- displayResult(C)
- .
- .
37Example
- Order matters big time see page 220
- Review tax example page 221
38Tips
- Code nested ifs one statement at a time.
- Code outer if then the internal ifs
- TEST TEST TEST
39Switch statement
- Switch allows you to select from several
alternatives. - Works especially well when based on the value of
one variable
40This 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.")
-
41Rules
- 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
42Another 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
43Returning 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.
44Repetition 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
45Overview
- Loops
- Counting loops
- Sentinel controlled loops
- Flag controlled loops
- Menu driven loops
- Loop types
- while
- for
- do-while
46Counting 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.
47While statement
- Syntax
- while (condition)
- statement
- Statement is the body of the loop
- Can be compound
- Condition, continues looping while condition
remains true
48Example
- int countTenSum 1
- int tenSum 0
- while (countTenSum lt 11)
- tenSum
- tenSum countTenSum
- countTenSum
- countTenSum 1
-
49Example
- 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
-
50Syntax and formatting
- while (repetitionCondition)
- loopBody
- Must use indentation for clarity
- As in other cases white space is totally ignored
by compiler
51Flow chart
countEmp lt numberEmp
Get Data Perform Calculations Increment counter
true
false
52Loop-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?
53For 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.
54While versus for
- counter initial
- While (counter lt final)
- //loop processing
- counter
- for (counter initial
- counter ltfinal
- counter)
- //loop processing
-
55Syntax 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
56For 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
57Accumulating 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
58New operators!!!
- count count 1
- count
- accum accum count
- accum count
- countDown countDown 1
- countDown--
59Code
- Review code on pages 234-236
60State-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??
61Code
- See exams pages 240 - 241
624.8 Case Study
- Problem
- Write program to generate and solve arithmetic
problems. - Has feature of varying difficulty
- Checks answers and corrects when wrong
63Analysis
- 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
64Analysis
- Another class will use MathProblem to generate
individual problems - Will also allow for looping and user interaction
- Will additionally store statistics
- Called MathDrill
65Design
- Table page 244
- Table page 245
66Implementation
67Section 4.9 Debugging and testing
- Jbuilder includes a Debugger that allows user to
- single-step through program
- trace
- set breakpoints
- watch variables
68Without debugger
- Use diagnostic output statements
- Put in println and showMessageDialog in
appropriate places in program to monitor code and
variables
694.10 Common Programming Errors
- Fully parenthesis your boolean expressions also
- boolean flag
- flag x y //works but should be
- flag (x y)
70Other common errors
- Watch use of versus
- Watch use of and indentation
- if (xy)
- x 2
- else
- y 3
- x 1
- //continue code here
71Other 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?