Page 62 - CTS - CSA TP - Volume 2
P. 62

COMPUTER SOFTWARE APPLICATION - CITS



           TASK 2: Guessing Game using do-while loop
           import java.util.Random;
           importjava.util.Scanner;
           public class DoWhileGuessingGame {
           public static void main(String[] args) {
                Scanner scanner = new Scanner(System.in);

             Random random = new Random();
           intsecretNumber = random.nextInt(100) + 1;
           int guess;
           int attempts = 0;
           System.out.println(“Guess the secret number between 1 and 100.”);
           do {
           System.out.print(“Enter your guess: “);
           guess = scanner.nextInt();
           attempts++;
           if (guess <secretNumber) {
           System.out.println(“Too low! Try again.”);
                    } else if (guess >secretNumber) {
           System.out.println(“Too high! Try again.”);
                    } else {
           System.out.println(“Congratulations! You guessed the secret number in “ + attempts + “ attempts.”);

                    }
                } while (guess != secretNumber);
           scanner.close();
             }
           }
           Output:


































                                                           47

                               CITS : IT & ITES - Computer Software Application - Exercise 87
   57   58   59   60   61   62   63   64   65   66   67