Multi-Selection: else-if Statements
Introduction: 3.4.0
- It is possible to pick between 3 or more possibilities
- Use
else if
! if
for the first possibilityelse if
for subsequent oneselse
for the last one
- Use
switch
andbreak
can also be used- Not covered on the exam
if (myExpr) {
doSomething();
} else if (myOtherExpr) {
doSomethingElse();
} else {
doThisOtherwise();
}
Summary: 3.4.2
- A multi-way selection is written when multiple condeitions with different statements for each one
- Performed with if-else-if statements
- Only the first condition which evaluates to true is executed
- Performed with if-else-if statements
/** method stub
@return day of week from 0 to 6
*/
public int getDayOfWeek()
int day = getDayOfWeek();
if (day == 4) {
System.out.println("Feliz Jueves!");
} else if (day > 0 && day < 6) {
// This isn't executed if day==4, even though that would also evaluate true here
System.out.println("It is a weekday. Go to school and learn Computer Science!");
} else {
System.out.println("It is the weekend! Don't forget to do your homework!");
}
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This was adapted from the CS Awesome curriculum, which was created by
Barbara Ericson, Beryl Hoffman, and many other CS Awesome contributors. All rights reserved.
CS Awesome is licensed under CC BY-NC-SA 4.0.