java · level 1 · unit 5 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Put an if inside a loop to check every number.
A loop's block can hold any code, an if. We say the if is inside the loop. The loop visits each number, and the if decides what to do with it.
Remember %, the remainder? A number is even when it splits into twos with nothing left over. So house % 2 == 0 is true for even numbers and false for odd ones.
To count matches, make a counter holding 0 before the loop. Each time the if finds a match, add one. Print the total after the loop.
public class Main {
public static void main(String[] args) {
int leaflets = 0;
for (int house = 1; house <= 6; house++) {
if (house % 2 == 0) {
System.out.println("Leaflet for house " + house);
leaflets++;
}
}
System.out.println("Leaflets posted: " + leaflets);
}
} Every { needs its own }, so close the if block before the loop's block.
guess first
Stomp or clap? Guess the rhythm.
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 beat = 1; beat <= 4; beat++) {
if (beat % 2 == 0) {
System.out.println("Clap");
} else {
System.out.println("Stomp");
}
}
}
}
your turn
Your turn. Hand out stickers.
Every few visitors get a sticker. Choose the gap on line 5, like 3 for every third visitor, then press run to count the stickers.
output
press run to see what happens
fix it
The house count went missing. Can you fix it?
output
press run to see what happens
- Java cannot find
lefton line 9. Where is that box made? - A box made inside a block only lives in that block, and it starts again at 0 every turn.
- Move
int left = 0;up above theforline, then press run.
nailed it
your loops can make decisions. :D
- An
ifcan sit nested inside a loop's block. number % 2 == 0istruefor even numbers.- Make the counter before the loop, then add one per match.
new words in your collection
- nested
- even
This lesson isn’t saved. A free account remembers every lesson you finish.