×

java · level 1 · unit 5 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.