Do-While Loop
The do-while loop is similar to the while loop, but it guarantees that the block of code will be executed at least once since the condition is evaluated after the execution of the loop body.
Apprentice · Java · Updated
The do-while loop is similar to the while loop, but it guarantees that the block of code will be executed at least once since the condition is evaluated after the execution of the loop body.
Example
Execute once and loop again if the user enters "yes"
import java.util.Scanner;
public class DoWhileLoopExample
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
String input;
do
{
// this block is guaranteed to execute at least once
System.out.println("Inside the loop.");
System.out.println("Do you want to go again? (yes/no)");
input = scanner.nextLine();
}
while (input.equalsIgnoreCase("yes"));
System.out.println("Loop ended.");
}
}
This loop ensures that the code inside the do block runs at least once irrespective of the condition, and then it continues to loop if the user inputs "yes".
Do it: count the scoreboard's digit boxes
A scoreboard shows each score in boxes, one digit per box. To set it up, the program needs to know how many boxes a score takes.
The function gets one value:
score: a team's score, anint(105). It's never below 0.
Each time through the loop, count one digit, then drop the score's last digit by dividing it by 10. (Dividing two ints keeps only the whole part, so 105 / 10 is 10.) For example, with 105:
| Time through | score at the start |
Digits counted | score / 10 |
|---|---|---|---|
| 1 | 105 | 1 | 10 |
| 2 | 10 | 2 | 1 |
| 3 | 1 | 3 | 0 |
The score is now 0, so the loop stops, and digitCount(105) returns 3.
A score of 0 still needs one box, to show the 0. That's why the loop must run at least once.
Your job: write the function int digitCount(int score) with a do-while loop.
- Each time through, add 1 to the count and divide the score by 10.
- Go again while the score is more than 0.
- Return the count.
- A score of 0 returns
1.
Practiced live on the lesson page: write the Java right there and check it.