Title: BCS2182 Object Oriented Programming
1MODULE 3 FLOW OF CONTROL
- COURSE CODE BCS2143
- COURSE NAME OBJECT ORIENTED PROGRAMMING
- LECTURER KHAIRUL ANWAR AJID
- CONTACT NO 2127 (ext)
2OBJECTIVES
- learn about Java branching statements
- learn about loops
- learn about the type boolean
- learn to use color and other graphic enhancements
3OUTLINE
- Branching Statements
- Java Loop Statements
- Programming with Loops
- The Type boolean
- Graphics Supplement
4FLOW OF CONTROL
- Flow of control is the order in which a program
performs actions. - Up to this point, the order has been sequential.
- A branching statement chooses between two or more
possible actions. - A loop statement repeats an action until a
stopping condition occurs.
5BRANCHING STATEMENTS OUTLINE
- The if-else Statement
- Introduction to Boolean Expressions
- Nested Statements and Compound Statements
- Multibranch if-else Statements
- The switch Statament
6The if-else Statement
- A branching statement that chooses between two
possible actions. - syntax
- if (Boolean_Expression)
- Statement_1
- else
- Statement_2
- example
- if (count lt 3)
- total 0
- else
- total total count
7The if-else Statement, cont.
8COMPOUND STATEMENTS
- To include multiple statements in a branch,
enclose the statements in braces. - if (count lt 3)
-
- total 0
- count 0
-
9Omitting the else Part
- If the else part is omitted and the expression
after the if is false, no action occurs. - syntax
- if (Boolean_Expression)
- Statement
- example
- if (weight gt ideal)
- caloriesPerDay - 500
10INTRODUCTION TO BOOLEAN EXPRESSIONS
- The value of a boolean expression is either true
or false. - examples
- time lt limit
- balance lt 0
11JAVA COMPARISON OPERATORS
12COMPOUND BOOLEAN EXPRESSIONS
- Boolean expressions can be combined using the
and () operator. - example
- if ((score gt 0) (score lt 100))
- ...
- not allowed
- if (0 lt score lt 100)
- ...
13COMPOUND BOOLEAN EXPRESSIONS, cont.
- syntax
- (Sub_Expression_1) (Sub_Expression_2)
- Parentheses often are used to enhance
readability. - The larger expression is true only when both of
the smaller expressions are true.
14COMPOUND BOOLEAN EXPRESSIONS, cont.
- Boolean expressions can be combined using the
or () operator. - example
- if ((quantity gt 5) (cost lt 10))
- ...
- syntax
- (Sub_Expression_1) (Sub_Expression_2)
15COMPOUND BOOLEAN EXPRESSIONS, cont.
- The larger expression is true
- when either of the smaller expressions is true
- when both of the smaller expressions are true.
- The Java version of or is the inclusive or
which allows either or both to be true. - The exclusive or allows one or the other, but not
both to be true.
16NEGATING A BOOLEAN EXPRESSION
- A boolean expression can be negated using the
not (!) operator. - syntax
- !(Boolean_Expression)
- example
- (a b) !(a b)
- which is the exclusive or
- Is it not true that programs which do not use the
not (!) operator are not easier to read?
17USING
- 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
objects have the same value. - if (s1 s2), where s1 and s2 refer to strings,
determines only if s1 and s2 refer the a common
memory location. - To test the equality of objects of class String,
use method equals. - s1.equals(s2) or s2.equals(s1)
- To test for equality ignoring case, use method
equalsIgnoreCase. - (Hello.equalsIgnoreCase(hello))
18equals and equalsIgnoreCase
- Syntax
- String.equals(Other_String)
- String.equalsIgnoreCase(Other_String)
19TESTING STRINGS FOR EQUALITY
20QUESTIONS
- Suppose goals is a variable of type int. Write an
if-else statement that outputs the word Wow if
the value of the variable goals is greater than
10 and outputs the words Oh Well if the value of
goals is at most 10. - Suppose goals and errors are variables of type
int. Write an if-else statement that outputs the
word Wow if the value of the variable goals is
greater than 10 and the value of errors is zero.
Otherwise, the if-else statement outputs the
words Oh Well. - Suppose salary and deductions are variables of
type double that have been given values. Write an
if-else statement that outputs OK and sets the
variable net equal to salary minus deductions,
provided that salary is at least as large as
deductions. If, however, salary is less than
deductions, the if-else statement simply outputs
the word Crazy and does not change the value of
any variables.
21ANSWERS
- if (goals gt 10)
- System.out.println("Wow")
- else
- System.out.println("Oh Well")
- if ((goals gt 10) (errors 0))
- System.out.println("Wow")
- else
- System.out.println("Oh Well")
- if (salary gt deductions)
-
- System.out.println("OK")
- net salary - deductions
-
- else
- System.out.println("Crazy")
22NESTED STATEMENTS
- An if-else statement can contain any sort of
statement within it. - In particular, it can contain another if-else
statement. - An if-else may be nested within the if part.
- An if-else may be nested within the else part.
- An if-else may be nested within both parts.
23NESTED STATEMENTS, cont.
- Syntax
- if (Boolean_Expression_1)
- if (Boolean_Expression_2)
- Statement_1)
- else
- Statement_2)
- else
- if (Boolean_Expression_3)
- Statement_3)
- else
- Statement_4)
24NESTED STATEMENTS, cont.
- Each else is paired with the nearest unmatched
if. - If used properly, indentation communicates which
if goes with which else. - Braces can be used like parentheses to group
statements.
25COMPOUND STATEMENTS
- When a list of statements is enclosed in braces
(), they form a single compound statement. - syntax
-
- Statement_1
- Statement_2
-
-
- A compound statement can be used wherever a
statement can be used. - example
- if (total gt 10)
-
- sum sum total
- total 0
26Multibranch if-else Statements
- Syntax
- if (Boolean_Expression_1)
- Statement_1
- else if (Boolean_Expression_2)
- Statement_2
- else if (Boolean_Expression_3)
- Statement_3
- else if
- else
- Default_Statement
27Multibranch if-else Statements, cont.
28Multibranch if-else Statements, cont.
29QA
- What output is produced by the following code?
- int time 2, tide 3
- if (time tide gt 6)
- System.out.println("Time and tide wait for
no one.") - else
- System.out.println("Time and tide wait for
me.") - Ans Time and tide wait for me.
- 2. What output is produced by the following code?
- int time 4, tide 3
- if (time tide gt 6)
- System.out.println("Time and tide wait for no
one.") - else
- System.out.println("Time and tide wait for
me.") - Ans Time and tide wait for no one.
- 3. What output is produced by the following code?
30The switch Statement
- The switch statement is a mutltiway branch that
makes a decision based on an integral (integer or
character) expression. - The switch statement begins with the keyword
switch followed by an integral expression in
parentheses and called the controlling
expression. - A list of cases follows, enclosed in braces.
- Each case consists of the keyword case followed
by - a constant called the case label
- a colon
- a list of statements.
31The switch Statement, cont.
- The list is searched for a case label matching
the controlling expression. - The action associated with a matching case label
is executed. - If no match is found, the case labeled default is
executed. - The default case is optional, but recommended,
even if it simply prints a message. - Repeated case labels are not allowed.
32The switch Statement, cont.
33The 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 controlling expression can be anything that
evaluates to an integral type. - Syntax
- switch (Controlling_Expression)
-
- case Case_Label
- Statement(s)
- break
- case Case_Label
-
- default
-
34QA
- 1. What output is produced by the following code?
- int code 2
- switch (code)
-
- case 1
- System.out.println("Hello.")
- case 3
- System.out.println("Good-bye.")
- break
- default
- System.out.println("Till we meet again.")
- break
-
- 2. Suppose you change the code in question 12 so
that the first line is the following - int code 1
- What output would be produced?
- 3. What output is produced by the following code?
35- Ans Till we meet again.
- Ans
- Hello
- Good-bye
- Ans Some kind of B.
36JAVA LOOP STATEMENTS OUTLINE
- the while Statement
- the do-while Statement
- the for Statement
37JAVA LOOP STATEMENTS, cont.
- A portion of a program that repeats a statement
or a group of statements is called a loop. - The statement or group of statements to be
repeated is called the body of the loop. - (e.g.)A loop could be used to compute grades for
each student in a class. - There must be a means of exiting the loop.
38The while Statement
- also called a while loop
- A while statement repeats until a controlling
boolean expression becomes false. - If the controlling boolean expression is false
initially, the while loop is not executed. - The loop body typically contains a statement that
ultimately causes the controlling boolean
expression to become false.
39The while Statement, cont.
40The while Statement, cont.
- Syntax
- while (Boolean_Expression)
- Body_Statement
- or
- while (Boolean_Expression)
-
- First_Statement
- Second_Statement
-
-
41The while Statement, cont.
42The do-while Statement
- also called a do-while loop
- similar to a while statement, except that the
loop body is executed at least once - syntax
- do
- Body_Statement
- while (Boolean_Expression)
- dont forget the semicolon!
43The do-while Statement, cont.
44The do-while Statement, cont.
- First, the loop body is executed.
- Then the boolean expression is checked.
- As long as it is true, the loop is executed
again. - If it is false, the loop is exited.
- equivalent while statement
- Statement(s)_S1
- while (Boolean_Condition)
- Statement(s)_S1
45The do-while Statement, cont.
46QA
- 1. What output will be produced by the following
code? - int count 0
- while (count lt 5)
-
- System.out.println(count)
- count
-
- System.out.println("count after loop "
count) - 2. Can the body of a while loop execute zero
times? Can the body of a do-while loop execute
zero times? - 3. What output will be produced by the following
code? - int count 0
- do
-
- System.out.println(count)
- count
- while (count lt 0)
- System.out.println("count after loop " count)
47Answer
- 1.
- 0
- 1
- 2
- 3
- 4
- count after loop 5
- 2. Yes, the body of a while loop can execute zero
times. No, the body of a dowhile loop must
execute at least once. - 3.
- 0
- count after loop 1
48The for Statement
- A for statement executes the body of a loop a
fixed number of times. - example
- for (count 1 count lt 3 count)
- System.out.println(count)
- System.out.println(Done)
- syntax
- for (Initialization, Condition, Update)
- Body_Statement
- Body_Statement can be either a simple statement
or a compound statement in . - corresponding while statement
- Initialization
- while (Condition)
- Body_Statement_Including_Update
49The for Statement, cont.
50The for Statement, cont.
51Multiple Initialization, etc.
- example
- for (n 1, p 1 n lt 10 n)
- p p n
- Only one boolean expression is allowed, but it
can consist of s, s, and !s. - Multiple update actions are allowed, too.
- for (n 1, p 1 n lt 10 n, p n)
52The Empty while Statement
- What is printed by
- int product 1, number 1
- while (number lt 2)
-
- product product number
- number
-
- System.out.println(product)
- The last semicolon in
- while (number lt 10)
- produces an empty while loop body.
53Choosing a Loop Statement
- If you know how many times the loop will be
iterated, use a for loop. - If you dont know how many times the loop will be
iterated, but - it could be zero, use a while loop
- it will be at least once, use a do-while loop.
- Generally, a while loop is a safe choice.
54QA
- 1. What output is produced by the following code?
- int n
- for (n 1 n lt 4 n)
- System.out.println(n)
- 2. What output is produced by the following code?
- int n
- for (n 1 n gt 4 n)
- System.out.println(n)
- 3. What output is produced by the following code?
- int n
- for (n 4 n gt 0 n--)
- System.out.println(n)
- 4. What output is produced by the following code?
- int n
- for (n 4 n gt 0 n--)
- System.out.println(n)
55Answer
- 1.
- 1
- 2
- 3
- 4
- 2. This loop causes no output. The boolean
expression n gt 4 is not satisfied the first - time through the loop, so the loop ends without
iterating its body. - 3.
- 4
- 3
- 2
- 1
- 4. The only output is
- 0
- Be sure to notice the semicolon that was added
at the end of the first line of the for loop.
56The break Statement in Loops
- A break statement can be used to end a loop
immediately. - The break statement ends only the innermost loop
or switch statement that contains the break
statement. - break statements make loops more difficult to
understand. - Use break statements sparingly (if ever).
57The break Statement in Loops, cont.
58The exit Method
- Sometimes a situation arises that makes
continuing the program pointless. - A program can be terminated normally by
- System.exit(0).
- example
- if (numberOfWinners 0)
-
- System.out.println(/ by 0)
- System.exit(0)
-
59Questions
- 1. What output is produced by the following code?
- int n
- for (n 1 n lt 5 n)
-
- if (n 3)
- break
- System.out.println("Hello")
-
- System.out.println("After the Loop.")
- 2. What output is produced by the following code?
- int n
- for (n 1 n lt 5 n)
-
- if (n 3)
- System.exit(0)
- System.out.println("Hello")
-
- System.out.println("After the Loop.")
Ans Hello Hello After the Loop
Ans Hello Hello
60QA
- 3. What output is produced by the following code?
- int n
- for (n 1 n lt 3 n)
-
- switch (n)
-
- case 1
- System.out.println("One.")
- break
- case 2
- System.out.println("Two.")
- break
- case 3
- System.out.println("Three.")
- break
- default
- System.out.println("Default case.")
- break
-
Ans One Two Three After the Loop.
61Programming with Loops Outline
- The Loop Body
- Initializing Statements
- Ending a Loop
- Loop Bugs
- Tracing Variables
62The Loop Body
- To design the loop body, write out the actions
the code must accomplish. - Then look for a repeated pattern.
- The pattern need not start with the first action.
- The repeated pattern will form the body of the
loop. - Some actions may need to be done after the
pattern stops repeating.
Output instructions to the user. Initialize
variables. Do the following for the appropriate
number of times Read a number into the
variable next. sum sum next
Output the number and the sum so far.
63Initializing Statements
Output instructions to the user. Initialize
variables. Do the following for the appropriate
number of times Read a number into the
variable next. sum sum next
Output the number and the sum so far.
- Some variables need to have a value before the
loop begins. - Sometimes this is determined by what is supposed
to happen after one loop iteration. - Often variables have an initial value of zero or
one, but not always. - Other variables get values only while the loop is
iterating.
for (count 1 count lt n count) Read a
number into the variable next. product
product next
64Ending a Loop
double next, average, sum 0 int count Scanner
keyboard new Scanner(System.in) for (count
1 count lt numberOfStudents count)
next keyboard.nextDouble() sum sum
next if (numberOfStudents gt 0) average
sum/numberOfStudents else
System.out.println("No scores to average.")
- If the number of iterations is known before the
loop starts, the loop is called a
count-controlled loop. - use a for loop.
- Asking the user before each iteration if it is
time to end the loop is called the
ask-before-iterating technique. - appropriate for a small number of iterations
- Use a while loop or a do-while loop.
do System.out.println("Enter price ")
price keyboard.nextDouble()
System.out.print("Enter number purchased ")
number keyboard.nextInt()
System.out.println(number " items at "
price) System.out.println("Total cost "
pricenumber) System.out.println("Want to
make another purchase?")
System.out.println("Enter yes or no.")
answer keyboard.next() while
(answer.equalsIgnoreCase("yes"))
65Ending a Loop, cont.
- For large input lists, a sentinel value can be
used to signal the end of the list. - The sentinel value must be different from all the
other possible inputs. - A negative number following a long list of
nonnegative exam scores could be suitable. - 100
- 90
- 10
- -1
System.out.println("Enter scores for all
students.") System.out.println("Enter a negative
number after") System.out.println("you have
entered all the scores.") Scanner keyboard new
Scanner(System.in) double max
keyboard.nextDouble() double min max//The max
and min so far are the first score. double next
keyboard.nextDouble() while (next gt 0)
if (next gt max) max next if (next
lt min) min next next
keyboard.nextDouble() System.out.println("The
highest score is " max) System.out.println("The
lowest score is " min)
66Ending a Loop, cont.
67Nested Loops
- The body of a loop can contain any kind of
statements, including another loop. - In the previous example
- the average score was computed using a while
loop. - This while loop was placed inside a do-while loop
so the process could be repeated for other sets
of exam scores.
68Declaring Variables Outside Loop Bodies
- The declaration of variables inside a loop body
is repeated with each execution of the loop body. - This can be inefficient, depending on the
compiler. - It the declaration of variables can be moved
outside the loop body, generally it is
appropriate to do so. (refer slide 66)
69QA
- Write a Java loop statement that will output the
phrase "One more time." to the screen four times.
Also, give any declarations or initializing
statements that are needed. - Ans int time
- for (time 1 time lt 4 time)
- System.out.println("One more time.")
- Give a Java loop statement that will set the
variable result equal to 25. Do this with a loop
that starts out with the value of result equal to
1 and multiplies the value of result by 2 for
each of 5 loop iterations. Also, give any
declarations or initializing statements that are
needed. - Ans int result 1
- int count
- for (count 1 count lt 5 count)
- result 2result
70- What output is produced by the following code
- int count, innerCount
- for (count 0 count lt 3 count)
- for (innerCount 0 innerCount lt count
innerCount) - System.out.println(innerCount)
- Ans
- 0
- 0
- 1
- 0
- 1
- 2
71Loop Bugs
- Common loop bugs
- unintended infinite loops
- off-by-one errors
- testing equality of floating-point numbers
72Subtle Infinite Loops
- Subtle infinite loops
- The loop may terminate for some input values, but
not for others. - For example (refer to figure below), you cant
get out of debt when the monthly penalty exceeds
the monthly payment. - Verify that the monthly payment exceeds the
penalty, for example, before entering a loop to
determine the number of payments needed to get
out of debt.
if (payment lt penalty) System.out.println("p
ayment is too small.") else count 0
while (balance lt 0) balance balance -
penalty balance balance payment count
System.out.println("You will have a
nonnegative balance in count"
months.")
count 0 while (balance lt 0) balance
balance - penalty balance balance
deposit count System.out.println("You
will have a nonnegative balance in
"count" months.") e.g., testing input
penalty 15, deposit 50
73Off-by-One Errors
- The loop body is repeated one too many times or
one too few times. - examples
- lt is used when lt should be used or lt is used
when lt should be used - using the index of the last character of a string
instead of the length of the string (or vice
versa) - easy to overlook
74Testing Equality of Floating-point Numbers
- works satisfactorily for integers and
characters. - is not reliable for floating-point numbers
(which are approximate quantities). - Use lt or gt rather than or !.
75Tracing Variables
- Tracing variables means watching the variables
change while the program is running. - Simply insert temporary output statements in your
program to print of the values of variables of
interest - or, learn to use the debugging
- facility that may be provided
- by your system.
count 0 System.out.println("count "
count)//trace System.out.println("balance "
balance)//trace System.out.println("penalty "
penalty)//trace System.out.println("deposit
" deposit)//trace while (balance lt 0)
balance balance penalty
System.out.println("balance penalty "
balance)//trace balance balance -
deposit System.out.println("balance -
deposit " balance)//trace count
System.out.println("count "
count)//trace System.out.println("Nonnegative
balance in count "
months.")
count 0 while (balance lt 0) balance
balance penalty balance balance -
deposit count System.out.println("Nonne
gative balance in " count "
months.")
76The Type Boolean.
- The type boolean is a primitive type with only
two values true and false. - Boolean variables can make programs more
readable.
if ((temperature lt 100) (thrust gt 12000)
(cabinPressure gt 30)) System.out.println("
Initiate launch sequence.") else
System.out.println("Abort launching sequence.")
if (systemsAreOK) System.out.println("Init
iate launch sequence.") else
System.out.println("Abort launching sequence.")
77Boolean Expressions and Variables
- Variables, constants, and expressions of type
boolean all evaluate to either true or false. - A boolean variable can be given the value of a
boolean expression by using an assignment
operator.
boolean isPositive (number gt 0) if
(isPositive) System.out.println("The number
is positive.") else System.out.println("The
number is negative or zero.")
is equivalent to
if (number gt 0) System.out.println("The number is
positive.") else System.out.println("The number
is negative or zero.")
78Naming Boolean Variables
- Choose a statement that will be true when the
value of the boolean expression is true, such as
isPositive or systemsAreOk. - Avoid names that do not unambiguously describe
the meaning of the value of the variable. Such as
numberSign, systemStatus.
79Truth Tables
80Precedence Rules
- Parentheses should be used to indicate the order
of operations. - When parentheses are omitted, the order of
operation is determined by precedence rules. - Operations with higher precedence are performed
before operations with lower precedence. - Operations with equal precedence are done
left-to-right (except for unary operations which
are done right-to-left).
81Precedence Rules, cont.
82Precedence Rules, cont.
- In what order are the operations performed?
- score lt min/2 - 10 score gt 90
- score lt (min/2) - 10 score gt 90
- score lt ((min/2) - 10) score gt 90
- (score lt ((min/2) - 10)) score gt 90
- (score lt ((min/2) - 10)) (score gt 90)
83Short-circuit Evaluation
- Sometimes only part of a boolean expression needs
to be evaluated to determine the value of the
entire expression. - If the first operand associated with an is
true, the expression is true. - If the first operand associated with an is
false, the expression is false. - This is called short-circuit or lazy evaluation.
84Short-circuit Evaluation, cont.
- Short-circuit evaluation is not only efficient,
sometimes it is essential! - A run-time error can result, for example, from an
attempt to divide by zero. - if ((number ! 0) (sum/number gt 5))
- Complete evaluation can be achieved by
substituting for or for .
85Input and Output of Boolean Values
- The values true and false of the type boolean can
be input and output in the same way that values
of the other primitive types, such as int and
double, - example
- boolean booleanVar false
- System.out.println(booleanVar)
- System.out.println("Enter a boolean value")
- Scanner keyboard new Scanner(System.in)
- booleanVar keyboard.nextBoolean()
- System.out.println("You entered " booleanVar)
- dialog
- false
- Enter a boolean value
- true
- You entered true
86Using a Boolean Variable to End a Loop
- Example
- boolean numbersLeftToRead true
- while (numbersLeftToRead)
-
- next keyboard.nextInt()
- if (next lt 0)
- numbersLeftToRead false
- else
- Process_Next_Number
-
87Using a Boolean Variable to End a Loop, cont
88- What output is produced by the following
statements? - int number 7
- boolean isPositive (number gt 0)
- if (number gt 0)
- number - 100
- if (isPositive)
- System.out.println("Positive.")
- else
- System.out.println("Not positive.")
-
- What output is produced by the following
statements? - System.out.println(true false)
- System.out.println(true false)
- System.out.println(true (x gt 0))
89Graphics Supplement Outline
- Specifying a Drawing Color
- The drawString Method
- A JOptionPane Yes/No Window
90Specifying a Drawing Color
- When drawing a shape inside an applets paint
method, think of the drawing being done with a
pen that can change colors. - The method setColor changes the color of the
pen. - canvas.setColor(Color.YELLOW)
- Drawings done later appear on top of drawings
done earlier.
91Specifying a Drawing Color, cont.
92Specifying a Drawing Color, cont.
93Programming Example
94Programming Example, cont.
- class MultipleFaces, contd.
95Programming Example, cont.
96The drawString Method
- similar to other drawing methods, but used to
draw text - canvas.drawString(Hello,10,20)
- syntax
- Graphics_Object.drawString(String, X, Y)
97A JOptionPane Yes/No Window
- used to present the user with a yes/no question
- The window contains
- the question text
- two buttons labeled Yes and No.
98A JOptionPane Yes/No Window, cont.
- example
- int answer JOptionPane.showConfirmDialog(null,
End program?, End Check, JOptionPane.YES_NO_OP
TION) - if (answer JOptionPane.YES_OPTION)
- System.exit(0)
- else
- System.out.println(once more)
99A JOptionPane Yes/No Window, cont.
100A JOptionPane Yes/No Window, cont.
- JOptionPane.showConfirmDialog returns an int
value named either YES_OPTION or NO_OPTION, but
you do not need to think of them as ints. - The second argument (End program? in our
example) appears in the window. - The third argument (End Check in our example)
is displayed as the title of the window.
101A JOptionPane Yes/No Window, cont.
- The last argument (JOptionPane.YES_NO_OPTION in
our example) requests a window with yes and no
buttons. - The first argument (null in our example) affects
the placement of the window on the screen. - Simply use null for now.
102Summary
- You have learned about Java branching statements.
- You have learned about loops.
- You have learned about the type boolean.
- You have learned to use color and the JOptionPane
yes/no window.