Sub topic 3
Run once before testing with do-while
A Java do-while loop runs its work before it checks whether to repeat. That means the loop enters its body at least once, even if the test would be false at the start.
This is useful when the first action must happen before a decision can be made. For example, a program may need to ask for a number before it can check whether the number is in the right range.
You will use a complete Java program in this chapter. To run it as shown, you need a Java development kit installed and a way to run commands in a terminal.
The order of a do-while loop
A loop repeats a group of statements. Each pass through that group is an iteration. The group of statements is the loop body.
A condition is a test whose result is either true or false. A do-while loop follows this order:
- Run the body.
- Test the condition.
- If the condition is
true, run the body again. - If the condition is
false, leave the loop and continue after it.
The condition is tested after every iteration, including the first one.
Write a do-while loop
The following program prints three numbers. Save it in a file named DoWhileCount.java.
public class DoWhileCount {
public static void main(String[] args) {
int count = 0;
do {
System.out.println(count);
count++;
} while (count < 3);
}
}Compile and run it from the folder that contains the file:
javac DoWhileCount.java
java DoWhileCountThe javac command prepares the Java file to run. The java command runs the program. The output is:
012
Look at the parts of the loop:
int count = 0;createscountand gives it a starting value.dobegins thedo-whilestatement.- The braces
{and}surround the body. System.out.println(count);prints the current value.count++adds one tocount. This is the update: it changes a value used by the loop.while (count < 3)tests whethercountis less than3.- The semicolon after the closing parenthesis ends the
do-whilestatement.
The loop tests count < 3 only after it prints and updates count. When the test is true, the program returns to the beginning of the body.
Trace the values
To trace a program is to follow its steps and record what happens. This table shows the value at each point in the loop.
| Iteration | Value printed | Value after `count++` | Is `count < 3` true? |
|---|---|---|---|
| First | `0` | `1` | Yes |
| Second | `1` | `2` | Yes |
| Third | `2` | `3` | No |
After the third test, the loop ends. The last value printed is 2, but the value of count after the loop is 3. The update happened after printing and before the final test.
Try a false starting condition
Change the starting line in DoWhileCount.java to int count = 3;. Save, compile, and run the program again.
The program prints 3 once. Then it adds one to count, making it 4. The test 4 < 3 is false, so the loop ends.
Notice that 3 < 3 is already false at the start. The program still enters the body, because it has not tested the condition yet. In this program, the test is actually made after the update, when count is 4.
If the body contains several statements, the program starts with the first one and follows them in order. An error inside the body can still stop the program before it reaches the condition.
Know when the test happens
A regular while loop tests its condition before entering its body. A do-while loop tests after entering its body.
| Loop | First condition test | If the condition is false at the start |
|---|---|---|
| `while` | Before the body | The body is skipped |
| `do-while` | After the body | The body is entered once |
Choose do-while when the first pass is needed before the program can make its decision. Asking for input is one example: the program needs a value before it can decide whether to ask again.
Choose a loop that tests first when the body must not run unless a condition is already true. For example, do not use the first pass of a do-while loop to perform an action that requires permission you have not yet checked.
Ask until a number is in range
Suppose a program needs a number from 1 through 5. It can ask once, check the answer, and ask again if the number is outside that range.
Save this program as ChooseNumber.java.
import java.util.Scanner;
public class ChooseNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
do {
System.out.print("Enter a whole number from 1 to 5: ");
number = input.nextInt();
} while (number < 1 || number > 5);
System.out.println("You chose " + number + ".");
input.close();
}
}Compile and run it:
javac ChooseNumber.java
java ChooseNumberA Scanner is a Java tool for reading input. The import line makes it available to this program. System.in is the program’s standard input, which is normally what you type in the terminal. The call input.nextInt() reads a whole number and stores it in number.
The program declares number before the loop. The body then gives it a value before the condition checks it. That lets the program use the same variable in both places.
The condition is number < 1 || number > 5. The symbol || means “or.” The whole condition is true if either test is true:
number < 1means the number is too small.number > 5means the number is too large.- If neither test is true, the number is in range.
For example, a user might enter these values:
| Number entered | Is it below `1` or above `5`? | What happens next? |
|---|---|---|
| `0` | Yes | Ask again |
| `6` | Yes | Ask again |
| `3` | No | Leave the loop and print the choice |
If the first number is 3, the loop still asks once. It then sees that 3 is in range and does not ask again.
Try the program with 1 and 5 too. Both are accepted because the condition uses < 1 and > 5, not <= 1 or >= 5.
Read the condition as a reason to repeat
In the number example, the condition describes an unwanted value. The loop repeats while the number is too small or too large. Once the number is acceptable, the condition becomes false and the loop ends.
This choice of wording matters. If the condition were number >= 1 && number <= 5, it would be true for an acceptable number. The loop would then ask again after a valid answer and stop after an invalid one. The symbol && means “and,” so both comparisons would need to be true.
When you write a condition, ask:
- What value should make the loop run again?
- Does the condition give
truefor that value? - What value should let the loop finish?
- Does the condition give
falsefor that value?
Test the values just inside and just outside the allowed range. For this program, 0, 1, 5, and 6 are useful checks.
Watch the update and the final test
In the counting example, the body changes count before the condition checks it. That order affects the output.
With count starting at 0, the test count < 3 allows another iteration after count becomes 1 and after it becomes 2. It stops after count becomes 3. Since printing happens before the update, the program prints 0, 1, and 2.
If you change the condition to count <= 3, then 3 <= 3 is true. The loop runs one more time and prints 3 as well. This is a common one-step boundary difference: < and <= do not include the same end value.
The update also needs to move the program toward a stopping point. If you remove count++ while count starts at 0, the condition count < 3 stays true. The program keeps printing 0.
In the input example, the new input is the update. The value can change each time the user types a number. If the user keeps entering numbers outside the range, the loop keeps asking. That is expected for this example.
Check the syntax
A do-while loop has a few details that are easy to miss:
- Write
dobefore the body. - Put the condition in parentheses after
while. - Put a semicolon after that closing parenthesis.
- Make sure the condition is a test that gives
trueorfalse. - Make sure a variable needed by the condition is available there. In the examples,
countandnumberare declared before their loops.
The semicolon in } while (count < 3); is part of the do-while statement. Do not leave it out.
Use braces around the body, as in the examples. They make it clear which statements run before each test.
Practice
Trace each loop in order: body first, condition second. Try each question before reading its answer.
Exercise
What does int n = 2; do { System.out.println(n); n++; } while (n < 4); print?
Show answer
It prints 2 and then 3. After printing 3, the update makes n equal to 4, so the condition is false.
Exercise
What does int n = 5; do { System.out.println(n); } while (n < 5); print?
Show answer
It prints 5 once. The body runs before the condition is tested, and 5 < 5 is false.
Exercise
A number must be from 1 through 5. What condition is true when number is outside that range?
Show answer
number < 1 || number > 5. It is true when the number is too small or too large.
Exercise
In the counting program, what happens if count starts at 0 and count++ is removed?
Show answer
The loop keeps printing 0 because count does not change and count < 3 stays true.