You are on page 1of 2

/*

* AUTHOR : MARK BRIAN D. BAUTISTA


* BSIT SET F ONLINE
*/
package labexer5a;

//All imports needed in the program


import java.util.InputMismatchException;
import java.util.Scanner;

public class LabExer5A {

public static void main(String[] args) {


//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.");
}
}

You might also like