3.1: Boolean Expressions | 3.2: If Control Flow | 3.3: If Else | 3.4: Else If | 3.5: Compound Booleans | 3.6: Equivalent Booleans | 3.7: Comparing Objects | 3.8: Homework |
Unit 3 Team Teach - 3.4
Unit 3 Team Teach
3.4 Else If Statements
Else If Statements: Used when you have multiple conditions that need to be checked sequentially.
Flow of Execution: Each condition is evaluated in the order written. The first true condition’s code runs, and the rest are skipped.
Structure:
- Start with a single if statement.
- Follow with as many else if statements as needed.
- Optionally end with one else to handle any remaining cases. Key Concept: The order of conditions matters. More specific conditions should come before broader ones to ensure accurate results.
int myAge = 17; // adjust the age too see the difference in what it prints out
System.out.println("Current age: " + myAge);
if (myAge >= 18)
{
System.out.println("You can registar to vote.");
System.out.println("You are old enough for a license to drive.");
}
else if (myAge >= 16) {
System.out.println("You are old enough for a license to drive.");
}
else if (myAge >= 15) {
System.out.println("You can learn to drive a car.");
}
else if (myAge >= 14) {
System.out.println("You are 14");
}
Current age: 17
You are old enough for a license to drive.
Raise your hand:
- If I was 19 what would it print out?
- If I was 13 what would it print out?
Popcorn Hack
Add more statements to make the code print out an “F” and “C”
public class gradeEvaluator
{
public static void main(String[] args)
{
double myAverage = 90;
System.out.println("Current average: " + myAverage);
if (myAverage >= 90)
{
System.out.println("You have \"A\" average.");
}
else if (myAverage >= 80)
{
System.out.println("You have an \"B\" average.");
}
//add more letter grade options as needed
}
}