1. Computing

Indeterminate Loops


Like determinate loops, indeterminate loops allow you to iterate over a code block until a certain condition is reached. The difference is that you use an indeterminate loop when you don't always know exactly how many times you need to loop. There are two options for this kind of loop - the do..while loop and while loop.

The do..while Loop

This loop is used when you know you want to execute the code inside the loop at least once. For example, say you want to get the user to input a number between 1 and 20. It's important that the user does this before the program continues. You can do this using a do..while loop:

//We can use an indeterminate do..while loop to keep asking the user to enter
//in a number. We don't know how many times we have to ask so a while loop
//is a good option.
boolean isNumber = false;
int number = 0;
    //Input dialog box allowing the user enter a number.
    String numberEntered = JOptionPane.showInputDialog(null, "Enter in a number between 1 and 20:"
        , "Number Validation", JOptionPane.QUESTION_MESSAGE);

        number = Integer.parseInt(numberEntered);
        if (number > 1 && number < 21)
            isNumber = true;
            tracker.append("Congratulations you entered in the number " + number + "\n");
            tracker.append("You didn't enter in a number between 1 and 20 \n");
    catch(NumberFormatException e)
        tracker.append("You didn't enter in a number\n");

Until the boolean variable isNumber is equal to true the loop will continue looping.

The while Loop

Now let's say you don't know if you want the loop to run once. It could be the case that the condition for looping has been met already. In that case you don't want the code inside the loop to execute. In these cases use the while loop. For example, let's say the user finally entered in a number between 1 and 20 (inclusive) and you want to count up from the number entered up to 20. If the user entered 20 then there is no count to be made so the loop doesn't need to run, but if the number was less than 20 then it does:

//Now that we have a number we can use a while loop to display all the
//numbers between it and 20
while (number <20)
    tracker.append("Counting up to 20.... I'm at.." + number + "\n");

If you want to see the do..while loop and while loop in action, have a look at the Going Loopy example program.

©2014 About.com. All rights reserved.