While Loops for Tracking Steps
Learn Java while loops by building a Daily Step Tracker that keeps asking for step counts, until the user finishes.
The project
You’ve just made the decision to live a healthier life by tracking your daily steps. Instead of entering your steps once and stopping, you want a system that keeps prompting you for your daily totals until you choose to finish. This is how a smartwatch works. Printing a single number, such as Steps today: 1,000
, can be useful, but it doesn’t show your overall progress. What you need is a loop: a system that keeps collecting your input until you tell it that you’re done, and which then reports the total steps you’ve taken so far.
Your project: Build a Daily Step Tracker in Java that collects steps day by day, adds them up, and stops only when the user chooses.
The programming concept
Suppose you’re a cashier. People keep coming up to you and asking, “How much does this cost?”
You don’t just answer once; you keep answering until the store closes.
That’s what a while
loop does: it keeps running while a condition is true.
Let’s see the while
loop in action. Try reading the code before pressing “Run.” What do you think will happen, and why?
public class LoopDemo {public static void main(String[] args) {int count = 1;while (count <= 5) {System.out.println("This is loop number " + count);count = count + 1;}}}