Codiqo

Learn Java · lesson 18 of 61 · about 8 minutes

while and do-while

Take the customer's money until the bill is paid: repeat code while a condition is true, and run a body at least once with do-while.

What you'll learn

  • Write a while loop
  • Write a do-while loop
  • Avoid infinite loops

Paying at the desk

The desk can work out the bill, but nobody has paid yet. The customer hands over money a bit at a time, a $50 note, then a $20, and the desk should keep taking it while the bill isn't covered. Nobody knows in advance how many times that will be. That's the job of a while loop.

Check, then run

while (cond) { ... } checks first, so it might run zero times. do { ... } while (cond); runs the body first, so it always runs at least once. Something inside must eventually make the condition false.

while

public class Main {
    public static void main(String[] args) {
        int fuel = 3;
        while (fuel > 0) {
            System.out.println("Fuel: " + fuel);
            fuel--;
        }
        System.out.println("Empty");
    }
}

Output

Fuel: 3
Fuel: 2
Fuel: 1
Empty

Step through it: paying a $15 bill with $10 notes

public class Main {
    public static void main(String[] args) {
        int bill = 1500;
        int paid = 0;
        while (paid < bill) {
            paid += 1000;
            System.out.println("Paid: " + paid);
        }
        System.out.println("Change: " + (paid - bill));
    }
}

Output

Paid: 1000
Paid: 2000
Change: 500

do-while: ask until valid

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n;
        do {
            System.out.print("Pick 1-3: ");
            n = in.nextInt();
        } while (n < 1 || n > 3);
        System.out.println();
        System.out.println("You picked " + n);
    }
}

Output

Pick 1-3: Pick 1-3: Pick 1-3:
You picked 2

while or do-while?

Use while when the body might not need to run at all: a bill that's already covered shouldn't take any more money. Use do-while when the body has to run before there's anything to check, like asking a question before you can test the answer.

Tip

Check every way out of a loop. The payment loop only ends when paid reaches the bill, so every lap has to add something to paid. A loop whose condition can never become false runs forever.

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.