do ... while

Figure 193. A do ... while loop Slide presentation Create comment in forum
int sum = 0, value;
do {
  System.out.print(
    "Enter value, 0 to terminate: ");
  value = scanner.nextInt();
  sum += value;
} while (0 != value);
System.out.println("Sum: " + sum);
Enter value, 0 to terminate: 3
Enter value, 0 to terminate: 1
Enter value, 0 to terminate: 0
Sum: 4
A do ... while loop


Figure 194. do ... while syntax Slide presentation Create comment in forum
do
  (block | statement)
while (booleanExpression);


exercise No. 66

Even or odd? Create comment in forum

Q:

Write an application which asks for integer values telling its user whether a given value is even or odd. Providing the special value 0 shall terminate your application:

Enter an integer (0 to terminate): 77
    77 is an odd number
Enter an integer (0 to terminate): -3
    -3 is an odd number
Enter an integer (0 to terminate): 26
    26 is an even number
Enter an integer (0 to terminate): 0
    0 is an even number
Goodbye!

Tip

  1. Use the modulo % operator.

  2. Choose an appropriate loop type with respect to your application's termination on user input «0».

A:

We obviously need a loop to ask for further input unless the last entered value was 0. In any case the loop's statement will be executed at least once:

Enter an integer (0 to terminate): 0
    0 is an even number
Goodbye!

A do ... while(...) rather than a while(...) loop is thus appropriate. It allows for entering the loop's body before any check is about to happen:

try(final Scanner scanner = new Scanner(System.in)){

  int userInput;
    do {
      System.out.print("Enter an integer (0 to terminate): ");
      userInput = scanner.nextInt();
      if (0 == userInput % 2) {
        System.out.println("    " + userInput + " is an even number");
      } else {
        System.out.println("    " + userInput + " is an odd number");
      }
    } while (0 != userInput);
  System.out.println("Goodbye!");
}