The document describes a program that generates a random secret number between 1 and 50. It prompts the user to guess the number and provides feedback on whether their guess is too high or too low. It tracks the number of attempts and prints a message if the user correctly guesses the number. The program handles input and number range exceptions to ensure valid guesses are entered between 1 and 50.
The document describes a program that generates a random secret number between 1 and 50. It prompts the user to guess the number and provides feedback on whether their guess is too high or too low. It tracks the number of attempts and prints a message if the user correctly guesses the number. The program handles input and number range exceptions to ensure valid guesses are entered between 1 and 50.
The document describes a program that generates a random secret number between 1 and 50. It prompts the user to guess the number and provides feedback on whether their guess is too high or too low. It tracks the number of attempts and prints a message if the user correctly guesses the number. The program handles input and number range exceptions to ensure valid guesses are entered between 1 and 50.
//Generating secret number from 1 to 50 int secretNumber = (int) (Math.random() * 49 + 1); int numoftries = 1; //counter for number of attemps
Scanner keyboard = new Scanner(System.in);
int guess = 0;
System.out.println("Guess a number from 1 to 50!");
do { try { guess = keyboard.nextInt(); //if the input number is less than 1 or greater than 50 if (guess < 1 || guess > 50) throw new OutOfRangeException(); //if the random number is guessed correctly if (guess == secretNumber) { System.out.println("You got it in " + numoftries + " attempt(s)!"); numoftries++; //if random number greater than the inout number } else if (guess < secretNumber) { System.out.println("Too low. Try again."); numoftries++; //if the random number is greater than the input number } else if (guess > secretNumber) { System.out.println("Too high. Try again."); numoftries++; } // Exception for mismatch input } catch (InputMismatchException ex) { System.out.println("Invalid input."); System.out.println("Guess a number from 1 to 50!"); keyboard.next(); //Throws exception if the number is less than 1 or greater than 50 } catch (OutOfRangeException oore) { System.out.println(oore.getMessage()); System.out.println("Guess a number from 1 to 50!"); } } while (guess != secretNumber); } } //Class for out of range exception class OutOfRangeException extends Exception { public OutOfRangeException() { super("Out of range."); } }