java · level 1 · unit 5 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
stops a loop early. skips a turn.
Sometimes you find what you need halfway through a loop. break stops the loop straight away, and Java carries on with the first line after it.
continue is gentler. It skips the rest of this turn only, then the loop moves on to the next one, like skipping a song you do not like.
Both usually sit inside an if, so they only happen when a condition is true.
public class Main {
public static void main(String[] args) {
for (int song = 1; song <= 5; song++) {
if (song == 4) {
break;
}
System.out.println("Playing song " + song);
}
System.out.println("Party over!");
}
} After break or continue, the rest of the block is skipped for that turn.
guess first
Skip a song. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
public static void main(String[] args) {
for (int song = 1; song <= 4; song++) {
if (song == 2) {
continue;
}
System.out.println("Playing song " + song);
}
}
}
your turn
Your turn. Find the golden ticket.
Choose which chocolate bar hides the golden ticket, from 1 to 10, on line 5. Press run and watch the unwrapping stop.
output
press run to see what happens
fix it
Cookie 3 is burnt, but the rest are fine. Fix it!
output
press run to see what happens
- Only cookies 1 and 2 get boxed. What happens to the loop at cookie 3?
breakstops the whole loop. You only want to skip this one cookie.- Change
breaktocontinueon line 5, then press run.
nailed it
you can stop a loop whenever you like. :D
breakstops the whole loop straight away.continueskips the rest of this turn only.- Put them inside an
ifso they happen at the right time.
new words in your collection
- break
- continue
This lesson isn’t saved. A free account remembers every lesson you finish.