π2.4: Multiway Selection
Table of Contents
π This page is a condensed version of CSAwesome Topic 2.4
Multiway Selection: Nested if
Statements
If statements can be nested inside other if statements, allowing for more possible branches in a program.
This is like asking a βfollow-up questionβ after passing an initial one.
if (boolean expression) {
// This "nested if" is evaluated when the outer is true
if (boolean expression) {
statement;
}
}
The boolean expression of the nested (inner)
if
statement is evaluated ONLY when the boolean expression of the outerif
statement evaluates totrue
.
Example: 20 Questions
Have you ever played 20 Questions? 20 Questions is a game where one person thinks of an object, and the other players ask up to 20 questions to guess what it is.
There is great online version called Akinator that guesses whether you are thinking of a real or fictional character by asking you questions. Akinator is a simple artificial intelligence algorithm that uses a decision tree of yes or no questions to pinpoint the answer.
Although Akinator needs a very large decision tree, we can create a guessing game for just animals using a much smaller number of
if
-statements.
Hereβs a simplified version of what the code might look like, using nested ifs:
βDanglingβ else
Problem
Sometimes with nested ifs we find a βdangling elseβ clause that could potentially belong to either if
statement. This may cause unintended behavior.
The rule is that the else
clause will always be a part of the closest unmatched if
statement in the same block of code, regardless of indentation.
// Nested if with dangling else
if (boolean expression)
if (boolean expression)
doThisStatement;
else // belongs to CLOSEST if
doThatStatement;
You can (and should) use curly braces ({}
) to enclose a nested if
like below:
if (boolean expression)
{
if (boolean expression)
doThisStatement;
}
else // belongs to FIRST if
doThatStatement;
Now the
else
clause belongs to the top levelif
block instead!
In fact many experienced Java programmers always use curly braces, even when they are not technically required, to avoid this kind of confusion.
Multiway Selection: else if
Blocks
With nested if/else structures, we can pick between 3 or more branches of code. Another type of multi-way selection is possible with else if
blocks. This is convenient when there are a series of mutually-exclusive expressions to be tested, with different segments of code for each condition.
Multi-way selection with else if
is performed such that no more than one segment of code is executed based on the first expression that evaluates to true in the block. If no expression evaluates to true, and there is a trailing else
statement provided, then the body of the else
is executed.
Syntax for multi-way selection with else if
:
if (boolean expression) {
statement1;
}
else if (boolean expression) {
statement2;
}
else {
statement3;
}
This structure can accomodate more than 3 choices easily β just add an
else if
clause for every possibility after the firstif
statement, and before the finalelse
block.
Here is a flowchart for a conditional structure with 3 options like in the code above:
Here is a code example of a conditional structure that implements else if
to test multiple possibilities for a single value:
int x = 2;
if (x < 0) {
System.out.println("x is negative");
}
else if (x == 0) {
System.out.println("x is 0");
}
else {
System.out.println("x is positive");
}
System.out.println("after conditional block");
Try changing the value of
x
to get each of the three possible lines in the conditional to print.
Another way to handle 3 or more conditional cases is to use the switch
and case
keywords, but these will not be on the exam. For a tutorial on using switch-case, see the Java Documentation.
- Initialize a variable
battery
of typeint
that represents your phone battery percentage. - Set up the structure of a conditional block with 4 possibilities, testing the value of
battery
. - Complete the code so the program prints:
"Unplug your phone!"
ifbattery > 95
"Plug in your phone!"
ifbattery < 50
"Low power mode!"
ifbattery <= 20
"All okay!"
otherwise
Separate if
Statements vs. else if
Chains
The core difference between multiple separate if
statements and connected else if
chains lies in their execution flow and the conditions under which their respective blocks of code are evaluated.
- An
else if
statement is always used in conjunction with an initialif
statement. - The conditions in an if/else-if/else chain are evaluated sequentially.
- Once a condition is found to be
true
, its corresponding code block is executed, and the rest of theelse if
andelse
blocks in that chain are skipped.
This structure is ideal for handling mutually exclusive conditions, where only one outcome is expected or desired from a set of possibilities.
This program uses 4 separate if
statements instead of the if/else-if
pattern. First, trace through the code to see why it prints out the incorrect grade. Then, fix it by adding else if
blocks to connect the conditions.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int score = scan.nextInt();
String grade = "";
if (score >= 90) {
grade = "A";
}
if (score >= 80) {
grade = "B";
}
if (score >= 70) {
grade = "C";
}
if (score >= 60) {
grade = "D";
}
else {
grade = "F";
}
System.out.println(grade);
}
}
Summary
- (AP 2.4.A.1) Nested if statements consist of if, if-else, or if-else-if statements within if, if-else, or if-else-if statements.
- (AP 2.4.A.2) The boolean expression (condition) of the inner nested if statement is evaluated only if the Boolean expression of the outer if statement evaluates to true.
- (AP 2.4.A.3) A multi-way selection (if/else-if) is used when there are a series of expressions with different segments of code for each condition. Multi-way selection is performed such that no more than one segment of code is executed based on the first expression that evaluates to true. If no expression evaluates to true and there is a trailing else statement, then the body of the else is executed.
// Multiway selection with else if
if (boolean expression) {
statement1;
}
else if (boolean expression) {
statement2;
}
else {
statement3;
}
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.