π3.4: Else If Statements
Table of Contents
π This page is a condensed version of CSAwesome Topic 3.4
π Take notes in a Codespace during class, coding along with the instructor.
- Go to GitHub and click on your picture in the TOP RIGHT corner
- Select
Your repositories
- Open
CS2-Unit-3-Notes
- Now on your repository, click and select the
Codespaces
tab - Click
Create Codespace on main
(unless you already have one listed there), wait for the environment to load, then youβre ready to code!
Multi-Selection: else-if Statements
Using if/else statements, you can even pick between 3 or more possibilites. Just add else if for each possibility after the first if, and else before the last possibility.
// 3 way choice with if, else if, else
if (boolean expression) {
statement1;
}
else if (boolean expression) {
statement2;
}
else {
statement3;
}
Run the code below and try changing the value of x
to get each of the three possible lines in the conditional to print.
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");
Here is a flowchart for a conditional with 3 options like in the code above:
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 see the Java Documentation.
Finish the following code so that it prints βPlug in your phone!β if the battery is below 50, βUnplug your phone!β if it is equal to 100, and βAll okay!β otherwise. Change the battery value to test all 3 conditions.
int battery = 60;
System.out.println("All okay!");
βοΈ Summary
-
A multi-way selection is written when there are a series of conditions with different statements for each condition.
-
Multi-way selection is performed using if-else-if statements such that exactly one section of code is executed based on the first condition that evaluates to true.
// 3 way choice with if, else if, else
if (boolean expression) {
statement1;
}
else if (boolean expression) {
statement2;
}
else {
statement3;
}
π When class ends, donβt forget to SAVE YOUR WORK!
- Navigate to the
Source Control
menu on the LEFT sidebar - Type a brief commit message in the box, for example:
updated Main.java
- Click the button on the LEFT menu
- Click the button on the LEFT menu
- Finally you can close your Codespace!
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.