java · level 1 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A loop keeps going while something is true.
A while loop is like an if that keeps coming back. It checks its condition, runs its block, then checks again. It stops the first time the condition is false.
Often a keeps track: a number box that changes each turn, like cookies = cookies - 1;. When it runs out, the condition turns false and the loop ends.
Forget to change the counter and the condition stays true forever. That is an : the program never finishes. Make sure something in the block moves it towards the end.
public class Main {
public static void main(String[] args) {
int cookies = 3;
while (cookies > 0) {
cookies = cookies - 1;
System.out.println("Nom! Cookies left: " + cookies);
}
System.out.println("All gone!");
}
} cookies-- takes one away, the same way cookies++ adds one.
guess first
Counting down. 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) {
int count = 3;
while (count > 0) {
System.out.println(count);
count = count - 1;
}
System.out.println("Blast off!");
}
}
your turn
Your turn. Run a countdown.
Choose a whole number to count down from on line 3, then type what happens at the end on line 8. Press run.
output
press run to see what happens
fix it
The trampoline will not start. Can you fix it?
output
press run to see what happens
- Java cannot find
jumps. Where is that box made? - A counter needs a box with a starting value before the loop can check it.
- Add
int jumps = 0;as a new line above thewhile, then press run.
nailed it
your loops know when to stop. :D
- A
whileloop repeats while its condition istrue. - Change the counter inside the block so the loop can end.
- A condition that never turns
falsemakes an infinite loop.
new words in your collection
- while
- counter
- infinite loop
This lesson isn’t saved. A free account remembers every lesson you finish.