while Loops & Your Mission
Repeat until the job's done, then put everything together.
while Loops & Your Mission 🎯
A for loop is great when you know how many times. A while loop keeps going as long as something is true, perfect when you don't know how long a job will take.
public class Main {
public static void main(String[] args) {
int battery = 100;
int laps = 0;
while (battery > 0) {
battery -= 30;
laps++;
}
System.out.println("Laps driven: " + laps);
}
}Trace it 🕵️: battery 100 → 70 → 40 → 10 → -20. That's 4 laps, then battery > 0 is false and the loop stops.
💡⚠️ Infinite loop alert! If nothing inside the loop changes
battery, the check is true forever and the loop never ends. Always change the thing you're checking.
🤖 Final mission: the field robot
Everything you've learned in one program: variables, math, if/else and a loop.
public class Main {
public static void main(String[] args) {
int plantsWatered = 0;
int water = 11; // liters in the tank
while (water >= 3) {
water -= 3;
plantsWatered++;
if (plantsWatered % 2 == 0) {
System.out.println("Plant " + plantsWatered + ": watered + checked soil");
} else {
System.out.println("Plant " + plantsWatered + ": watered");
}
}
System.out.println("Water left: " + water + " liters");
}
}Can you predict all four lines before you run it? (Hint: trace water and plantsWatered, and remember what % 2 == 0 means.)
🎉 You did it!
You can now write Java that talks, remembers, calculates, decides and repeats. These are the same building blocks used to program real competition robots.
Ready for more? Our live Java Programming for Kids class builds on exactly this with a teacher, through robotics-inspired projects. Ask us about the next Java class →
Want to run it yourself?
Predict what the code prints first, then check! Copy an example above, paste it into the free online Java editor, and press Run. Keep the first line as public class Main.
Opens Programiz, a free site that isn't run by First Coding Path and may show ads. Grown-ups, you might like to take a look first.