Using Do..While Loops
Do..While Loops
Do..while loops are considered post-test loops. Similar to while loops, do..while loops can be used to iterate a set number of times or until a condition is met, like a user enters a particular value or clicks on a desired object. The do..while loop checks the Boolean expression after executing the statements in the body of the loop and only repeat these statements if the Boolean expression at the end evaluates to true, otherwise the iteration doesn't happen.
Because a do..while loop is a post-test loop, it executes the statements in the body of the loop at least once.
In some of the while loop examples, we needed to use if statements to avoid incorporating the values that were meant to end the loop into the algorithm. This can sometimes be avoided by using a do..while instead.
The general format of a do..while loop is as follows:
do {
//statements we want to repeat
} while (<boolean expression>);
Tracing Do..While Loops
Let's look at the same while loop examples, re-written as do..while loops:
Your Turn
Let's try it in the Java Playground
- Trace the code and predict the output of the code.
- Run the code to determine if your prediction is correct.
- Modify
value to be assigned 10. Predict the output of the code. Run the code to determine if your prediction is correct.
- Modify
value to be assigned 11. Predict the output of the code. Run the code to detemrine if your prediction is correct.
- Modify
value to be assigned 0 and value += 2 to be value -= 2. Predict the output of the code. Run the code to determine if your prediciton is correct.
Prompting For a Positive Valuea
The following code continues to read in values until a positive value is entered. This is a way that you can safeguard your program against users not entering the right type of data. Some examples of where you might have experienced a program safeguarding your input, is if you sign up for an account and you haven't filled in all the required fields, it will keep prompting you to do so until all the currently blank required fields have values.
int value;
do {
String input = IO.readln("Enter a positive number");
value = Integer.parseInt(input);
} while (value <= 0);
Computing Your Average
The following program prompts the user to enter in grades or 999 if no more grades are available. It updates totalGrades by adding each grade to the total and increases numGrades by 1. Once all the grades are entered, it computes the average. It's important to initialize the totalGrades and numGrades to 0 before any grades are entered. These variables need an initial value in order to be a part of a sum. The variable totalGrades is assigned to 0 since no grades have been entered yet. The value of numGrades is set to -1, because this algorithm will increase numGrades by 1 the first time through the loop even though no grades have been entered yet. By offsetting numGrades by 1, once a grade is entered, we will have an accurate count of grades. The variable grades is set to 0 since we haven't had a grade entered yet and this value gets added to totalGrades.
int totalGrades = 0;
int numGrades = -1;
int grade = 0;
do {
totalGrades += grade;
numGrades++;
String input = IO.readln("Enter a grade. Enter 999 to stop.");
grade = Integer.parseInt(input);
} while (grade != 999);
if (numGrades != 0) {
IO.print(totalGrades/numGrades);
}
Spending Calculator
This program keeps track of your available spending money and subtracts your purchases. The loop ends if there are no more purchases or if the amount of spending money is less than or equal to 0. The value of spendingMoney starts out at $100 and is updated for each purchase made. This program assumes that at least one purchase has been made that requires spendingMoney to be updated.
int spendingMoney = 100;
int purchaseAmount = 0;
String morePurchases = "yes";
do {
String input = IO.readln("How much money did you spend?");
purchaseAmount = Integer.parseInt(input);
spendingMoney -= purchaseAmount;
morePurchases = IO.readln("Do you have more purchases? Enter true for yes, false for no.");
} while (morePurchases.equals("yes") && spendingMoney > 0);
IO.println("You have $" + spendingMoney + " left.");
Resources
Next Learn Tutorial