Java Control-flow Sunulan 2024 Pylş
Java Control-flow Sunulan 2024 Pylş
• x == y: x equals y
• ( equality: ==, assignment: = )
Boolean operators
• &&: logical AND
• ||: logical OR
Multibranch 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
Compound Boolean
Expressions
• Boolean expressions can be combined using
the “and” (&&) operator.
• example
if ((score > 0) && (score <= 100))
...
• not allowed
if (0 < score <= 100)
...
Negating 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
Nested 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.
Nested 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);
The switch Statement
• The switch statement is a multiway branch
that makes a decision based on an integral
(integer or character) expression.
System.out.println(product);?
• Example
if (numberOfWinners == 0)
{
System.out.println(“/ by 0”);
System.exit(0);
}
Embedded Loops
Ending a Loop
• 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.
Ending 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.
90
0
10
-1
Example: class ExamAverager
Naming Boolean Variables
• Choose names such as isPositive or
systemsAreOk.
• Avoid names such as numberSign or
systemStatus.
Precedence Rules in Boolean
Expressions
Precedence Rules, cont.
• In what order are the operations
performed?