Chap 3 Java 6 TH
Chap 3 Java 6 TH
Flow of Control
else if (Boolean_Expression_n)
Statement_n
else
Statement_For_All_Other_Possibilities
switch (Controlling_Expression)
{
case Case_Label_1:
Statement_Sequence_1
break;
case Case_Label_2:
Statement_Sequence_2
break;
...
case Case_Label_n:
Statement_Sequence_n
break;
default:
Default_Statement Sequence
break;
}
• Java can take a shortcut when the evaluation of the first part
of a Boolean expression produces a result that evaluation of
the second part cannot change
• This is called short-circuit evaluation or lazy evaluation
– For example, when evaluating two Boolean subexpressions joined by
&&, if the first subexpression evaluates to false, then the entire
expression will evaluate to false, no matter the value of the second
subexpression
– In like manner, when evaluating two Boolean subexpressions joined by
||, if the first subexpression evaluates to true, then the entire
expression will evaluate to true
Statement_Last
}
Statement_Last
...
} while (Boolean_Expression);
Statements;
while (Boolean condition)
{
Statements;
}
if (Boolean condition)
{
do
{
Statements;
} while (Boolean condition);
}
do
{
System.out.println("Enter 'A' for option A or 'B' for option B.");
s = keyboard.next();
s.toLowerCase();
c = s.substring(0,1);
}
while ((c != 'a') || (c != 'b'));
do
{
System.out.println("Enter 'A' for option A or 'B' for option B.");
s = keyboard.next();
s.toLowerCase();
c = s.charAt(0);
}
while ((c != 'a') || (c != 'b'));
Now the program compiles, but it is stuck in an infinite loop. Employ tracing:
Sample output:
Enter 'A' for option A or 'B' for option B.
A
String s = A
Lowercase s = A
c = A
Enter 'A' for option A or 'B' for option B.
From tracing we can see that the string is never changed to lowercase.
Reassign the lowercase string back to s.
Copyright © 2016 Pearson Inc. All rights reserved. 3-54
Debugging Example (5 of 9)
• The following code is supposed to present a
menu and get user input until either ‘a’ or ‘b’
is entered.
do
{
System.out.println("Enter 'A' for option A or 'B' for option B.");
s = keyboard.next();
s = s.toLowerCase();
c = s.charAt(0);
}
while ((c != 'a') || (c != 'b'));
This works, but it is ugly! Considered a coding atrocity, it doesn’t fix the
underlying problem. The boolean condition after the while loop has also
become meaningless. Try more tracing:
Sample output:
Enter 'A' for option A or 'B' for option B.
A
c != 'a' is false
c != 'b' is true
(c != 'a') || (c != 'b')) is true
From the trace we can see that the loop’s boolean expression is true because c
cannot be not equal to ‘a’ and not equal to ‘b’ at the same time.
Copyright © 2016 Pearson Inc. All rights reserved. 3-57
Debugging Example (8 of 9)
• Fix: We use && instead of ||
do
{
System.out.println("Enter 'A' for option A or 'B' for option B.");
s = keyboard.next();
s = s.toLowerCase();
c = s.charAt(0);
}
while ((c != 'a') && (c != 'b'));