4.3 The do while loop

The do while loop is similar to the while loop with an important difference: the do while loop performs a test after each execution of the loop body.
import java.util.Scanner; // needed for Scanner Class

/**
 * This program demonstrate do while loop.
 */
public class AddNumbers
{
   public static void main(String[] args)
   {
      int  value;      // to hold data entered by the user
      int  sum = 0;    // initialize the sum
      char choice;     // to hold 'y' or 'n'

      // Create a Scanner object for keyboard input.
      Scanner console = new Scanner(System.in);

      do
      {
         // Get the value from the user.
         System.out.print("Enter integer: ");
         value = console.nextInt();

         // add value to sum
         sum = sum + value;

         // Get the choice from the user to add more number
         System.out.print("Enter Y for yes or N for no: ");
         choice = console.next().charAt(0);
      }
      while ((choice == 'y') || (choice == 'Y'));

      //Display the total.      
      System.out.println("Sum of the integers: " + sum);
   }
}
Output :
Enter integer: 6
Enter Y for yes or N for no: y
Enter integer: 8
Enter Y for yes or N for no: y
Enter integer: 4
Enter Y for yes or N for no: n
Sum of the integers: 18

Following example uses a do while loop to implement the Guessing the Number game. The program gives as many tries as the user needs to guess the number.
import java.util.Scanner; // needed for Scanner Class

/**
 * This program implements number guessing game.
 */
public class GuessMyNumber
{
   public static void main(String[] args)
   {
      int num;      // to hold random number
      int guess;    // to hold the number guessed by the user

      // Create a Scanner object for keyboard input.
      Scanner console = new Scanner(System.in);

      // Get random number between 1 to 100.
      num = (int) (Math.random() * 100) + 1;

      do
      {
         System.out.print("Enter an integer between 1 to 100: ");
         guess = console.nextInt();

         if (guess == num)
         {
            System.out.println("You guessed the correct number.");
         }
         else if (guess < num)
         {
            System.out.println(
                "Your guess is lower than the number.\nGuess again!");
         }
         else
         {
            System.out.println(
                "Your guess is higher than the number.\nGuess again!");
         }
      }
      while (guess != num);
   }
}
Output :
Enter an integer between 1 to 100: 56
Your guess is higher than the number.
Guess again!
Enter an integer between 1 to 100: 23
Your guess is higher than the number.
Guess again!
Enter an integer between 1 to 100: 10
Your guess is lower than the number.
Guess again!
Enter an integer between 1 to 100: 21
Your guess is higher than the number.
Guess again!
Enter an integer between 1 to 100: 20
You guessed the correct number.

No comments:

Post a Comment

Pages