Skip to main content
Engineering LibreTexts

15.6: The do-while Loop

  • Page ID
    15254
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    The while and for statements are pretest loops; that is, they test the condition first and at the beginning of each pass through the loop.

    Java also provides a posttest loop: the do-while statement. This type of loop is useful when you need to run the body of the loop at least once.

    For example, in Section 5.7 we used the return statement to avoid reading invalid input from the user. We can use a do-while loop to keep reading input until it’s valid:

    Scanner in = new Scanner(System.in);
    boolean okay;
    do {
        System.out.print("Enter a number: ");
        if (in.hasNextDouble()) {
            okay = true;
        } else {
            okay = false;
            String word = in.next();
            System.err.println(word + " is not a number");
        }
    } while (!okay);
    double x = in.nextDouble();
    

    Although this code looks complicated, it is essentially only three steps:

    1. Display a prompt.
    2. Check the input; if invalid, display an error and start over.
    3. Read the input.

    The code uses a flag variable, okay, to indicate whether we need to repeat the loop body. If hasNextDouble() returns false, we consume the invalid input by calling next(). We then display an error message via System.err. The loop terminates when hasNextDouble() return true.


    This page titled 15.6: The do-while Loop is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) .

    • Was this article helpful?