java · level 1 · unit 4 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
is the other path at the fork.
An if on its own either runs its block or skips it. Often you want a plan B. else means otherwise: when the condition is false, Java runs the else block instead.
At a fork you always take exactly one path. With if and else, exactly one block runs. Never both, and never neither.
else comes straight after the closing curly bracket of the if. It has no condition of its own, and its lines sit in their own curly brackets.
public class Main {
public static void main(String[] args) {
int biscuits = 0;
if (biscuits == 0) {
System.out.println("Time to go to the shop.");
} else {
System.out.println("Have a biscuit!");
}
}
} Read else as otherwise.
guess first
Out of lives? Make a guess.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
public static void main(String[] args) {
int lives = 0;
boolean gameOver = lives == 0;
if (gameOver) {
System.out.println("Game over!");
} else {
System.out.println("Keep playing!");
}
}
}
your turn
Your turn. Head to the cinema.
Type how many cinema tickets you have on line 3, any whole number except 0. Then press run to see plan B.
output
press run to see what happens
fix it
The cinema code will not run. Fix it!
output
press run to see what happens
- Java says it found an
elsewithout anif. Look closely at the end of line 4. - A semicolon ends an instruction. Straight after the
ifbrackets, it cuts theifoff from its block. - Delete the
;after(tickets == 0)on line 4, then press run.
nailed it
your program has a plan b now. :D
elseruns when theifcondition isfalse.- Only one block runs: the
ifone or theelseone. - Never put a semicolon straight after the
ifbrackets.
new words in your collection
- else
This lesson isn’t saved. A free account remembers every lesson you finish.