The do-while statement is similar to a while loop except that the body of the loop always executes at least once. It consists of the do
keyword followed by a statement, the while
keyword, and then a logical expression enclosed in parentheses:
do <statement> while (<boolean-expression>);
Typically, the body of the do-while loop, as represented by the statement, is a block statement. The following code snippet illustrates the use of the do statement. It is an improvement over the equivalent while loop used in the previous section, as it avoids prompting for a number before the loop starts:
int sum = 0; int number; Scanner scanner = new Scanner(System.in); do { System.out.print("Enter a number: "); number = scanner.nextInt(); if(number > 0 ) { sum += number; } } while (number > 0); System.out.println("The sum is " + sum);
When executed you should get output similar to the following:
Enter a number: 8 Enter a number: 12 Enter a number: 4...