Unit3 Home | Unit3 3.1 | Unit3 3.2 | Unit3 3.3 | Unit3 3.4 | Unit3 3.5 | Unit3 3.6 | Unit3 3.7 | Unit3 HW |
Unit 3 Team Teach - 3.3
Unit 3 Team Teach
3.3 If Else Statements
Purpose of Else Statements
Else statements: Handles what happens when the if condition is false. Structure of If-Else:
- If statement with a condition.
- Else statement without a condition.
- Both parts have code blocks surrounded by {}.
don’t forget the brackets
int x = 20;
if (x > 10) {
console.log("x is greater than 10");
console.log("This code when the condition is true");
} else {
console.log("x is 10 or less");
console.log("This code runs when the condition is false");
}
// Without brackets:
console.log("x is greater than 10");
console.log("this code will always run");
- Based on this code, if you were younger than 16 what would it print out?
- Write your own if else statement
answer
- Based on this code, if I was younger than 16, the output should be the second one: “You are not old enough for a license yet.”
- ↓↓↓
public static void main(String[] args) {
double myHeight = 5.7;
System.out.println("Current height: " + myHeight);
if (myHeight >= 5.7) {
System.out.println("You can ride this dangerous ride in DNHS.");
} else {
System.out.println("You are not tall enough to ride this dangerous ride in DNHS.");
}
}
main(null);
Current height: 5.7
You can ride this dangerous ride in DNHS.