The do..while loop is another type of conditional loop and is very similar to the while loop except the loop continuation condition is at the bottom of the loop rather than at the top. For this reason, it’s referred to as a post-test loop.
Here’s an example that continuously prompts a user for an integer until they enter a value between 1 and 10 (inclusive).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.Scanner; public class DoLoop { public static void main( String[] args ) { Scanner input = new Scanner( System.in ); int number; // Require user to enter integer between 1..10 (inclusive) do { System.out.print( "Pick an integer between 1 and 10: " ); number = input.nextInt(); } while ( ( number < 1 ) || ( number > 10 ) ); System.out.println( number + " is an excellent choice!" ); } } |
Pick an integer between 1 and 10: 12
Pick an integer between 1 and 10: -2
Pick an integer between 1 and 10: 7
7 is an excellent choice!
Notice that the while keyword is outside the curly braces { .. } and is terminated with a semi-colon (;). Because the loop continuation condition is checked at the bottom of the do..while loop, the body of the loop is guaranteed to iterate at least once. In practice, while loops are more commonly used than do..while loops.
The example above is an excellent example of input validation. Input validation is a programming technique where we check input to our program and only accept valid input before proceeding. This is a proactive approach to avoiding run-time errors from happening. You may have heard the acronym “GIGO”. This stands for Garbage-In, Garbage-Out. In other words, if we accept invalid input to our programs we should expect to get invalid output back.
Which Loop is Best?
I know what you’re thinking: “These loops are all so beautiful! How can one possibly choose between them?” Yes, I know exactly how you feel… Although they all provide the same basic function, to repeat code, they are slightly different in their implementations. Let’s summarize:
-
- for loop: is best when we know, before we start the loop, exactly how many repetitions we need. The for loop is ideal for counter-controlled loops.
- while loop: is best when we do not know how many times the loop will need to repeat, and where the loop may not execute at all if the loop continuation condition is false In other words, the body of the loop may be repeated 0 or more times. While loops are best suited as condition-controlled loops.
- do..while loop: is best when we do not know how many times the loop will need to repeat, but we want the body of the loop to execute at least once before checking the loop continuation condition. In other words, the body of the loop will be repeated at least 1 or more times. Do..while loops are also ideal for condition-controlled loop situations.
Again, these are only guidelines. For example, depending on how you design it, a while loop could behave like a counter-controlled (for) loop, and vice versa.
An Infinite Loop
A common logic error when designing loops is accidentally creating what is called an infinite loop. An infinite loop is a loop that never terminates because for some reason the loop continuation condition never becomes false. See if you can spot the logic problem here:
1 2 3 4 5 6 7 8 9 10 11 |
public class InfiniteLoop { public static void main( String[] args ) { int oddNumber = 1; System.out.print( "Odd Numbers between 1 and 10: " ); while (oddNumber != 10) { System.out.print( oddNumber + " " ); oddNumber = oddNumber + 2; } } } |
Don’t run this yet! The problem here is that the loop continuation condition is too focused. Since we start oddNumber at 1 and add 2 each time the loop body iterates, it will never have a value of exactly 10 and the loop will iterate forever. To fix this logic error the condition should be more general: (oddNumber < 10). If your code gets into an endless loop, click the button in Dr Java.
You Try!
-
- Convert the following do..while loop to a while loop.
123456789101112Scanner keyboard = new Scanner( System.in );String input;char key;do {System.out.print("Do you want to quit? ");input = keyboard.next();// Get the first character from the input stringkey = input.charAt(0);} while (key != 'Y' && key != 'N');System.out.printf( "You entered: %c\n", key); - Write a program that displays the following patterns separately, one below the other. You may use any loop structure that you like, but I would recommend trying different loop structures to get the most out of this exercise.
- Convert the following do..while loop to a while loop.