Logout

The Do While Loop

The do while loop is the third of the looping control sturctures we'll look at. The while loop and the for loop were looked at earlier, but the do while loop was left until now so as not to muddy the waters too much earlier on.

The structure of the do while loop is:

Which looks like the following example:


boolean continue = true;
do{
    System.out.println("Looping some more.");
    System.out.println("Would you like to continue? true/false);
    continue = Boolean.parseBoolean(br.readLine());
}while(continue);

for, while, and do while, All Accomplish Iteration

It is true that all three looping control structures can accomplish the same thing, as will be shown next. But it is important to note that this is just a classic, cute example to demonstrate that all three perform iteration. Really, you would never do what is seen below for the while and do whiles since the looping is done according to definite ints, and so the exact number of times the loops will execute is known.


for(int i = 0; i < 4; i++){
            System.out.println(i);
}


int i1 = 0;
while(i1 < 4){
    System.out.println(i1);
    i1++;
}


int i2 = 0;
do{
    System.out.println(i2);
    i2++;
}while(i2 <4);

These three all print out:

0
1
2
3

But again, you should not actually use while and do while loops for such definite looping; they should be used only when the number of times the loop will iterate is unknown.

When to Use a Do While Loop

The do while loop is a variation of the while loop. So, like the while loop, it is used when the number of times a loop will iterate is unknown. Refer to the "When to Use a While Loop" notes from the first spiral for a review of when to use a while loop. The same general principle of "when the number of iterations is unknown" applies for a do while. So, if you know the exact number of times you wish the loop to loop, you use a for loop; otherwise you use either a while or a do while loop.

What makes the do while loop different than a while loop is that, the loop will always iterate at least once. This is because the condition for continuing is checked after the block of code, not before it. So, when to use each? Basically, it's that simple: if you are sure the loop should be entered at least once, you should use a do while.

The do while's checking the continuation condition at the end of the block offers two advantages. First of all the code which sets up the boolean value of the conditional statement only has to be written once, inside the loop block, whereas in a while loop, that code has to be before the while condition, and also inside the loop block. So in the case of the do while, not only does this save lines of code, it prevents errors that could occur if that code is changed in the one place, but not in the other. The other advantage of the do while loop is that it more naturally reflects a real-life situation where something is done before the first check of a condition for continuation.

An classic example of where the condition for continuation occurs after one iteration is the input of a password. The password is typed in before the condition for continuation is checked. And then, if the password is wrong, iteration occurs.

            
            boolean continueLooping = true;
            do {
                System.out.println("Enter your password");
                String password = br.readLine();
                if (password.equals("abc123")) {
                    continueLooping = false;
                }
            } while (continueLooping);


The above example is lacking a few things to make it truly functional. For example, at this point the user could type in wrong passwords indefinitely. The other thing missing is a variable to keep track of whether or not the user does indeed type in the correct password. So, just for the sense of completion, below is a fully functional block of code for checking for correct passwordes, including the do while loop.


public static void main(String[] args) {

        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            boolean continueLooping = true;
            boolean passwordCorrect = false;
            int numTrys = 0;
            do {
                System.out.println("Enter your password");
                String password = br.readLine();
                if (password.equals("abc123") || numTrys > 2) {
                    continueLooping = false;
                }
                if(password.equals("abc123")){
                    passwordCorrect = true;
                }
                numTrys++;
            } while (continueLooping);
            if(passwordCorrect){
                System.out.println("Welcome to the secure part of our site");
            }
            else{
                System.out.println("Sorry, after four trys you did not get the password correct, so you cannot proceed further.");
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());

        }
    }