Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Exception Handling This program must be written as a console application. GUI pr

ID: 3856916 • Letter: E

Question

Exception Handling

This program must be written as a console application. GUI projects will not be accepted.

The "high-low" guessing game. How it works: The user attempts to guess a random generated number by the program. If the number is too high, then the program will display "too high." If the number is too low, then the program will display "too low." This will continue until the user correctly guesses the number. Your task for this assignment is to implement a guessing game using exceptions. Implement an exception-handling console application with the following: Program generates random number that the user tries to guess. User enters guess. Program generates tooHigh, tooLow or correct exceptions. You must write custom exception classes for each of these situation (For example: TooHigh.java, TooLow.java) Exception handler throws appropriate exception and a response is issued from the exception class using the getMessage() method. User is allowed to continue guessing and evaluation is repeated until correct guess is made.

Explanation / Answer

import java.util.Random;
import java.util.Scanner;


public class HighLow {

   public static void main(String[] args) {
       Random rand = new Random();
       Scanner sc = new Scanner(System.in);
       int num = Math.abs(rand.nextInt(1000));
      
       int guess = -1;
       while(guess != num){
           try{
           System.out.println("Enter your guess: ");
           guess = sc.nextInt();
           if(guess==num){
               System.out.println("CORRECT");
               break;
           }
           else if(guess<num){
               throw new TooLow("Too Low");
           }
           else if(guess>num){
               throw new TooHigh("Too high");
           }
           }
           catch(TooLow tl){
               //tl.printStackTrace();
               System.out.println("TOO LOW");
               continue;
           }
           catch(TooHigh th){
               //th.printStackTrace();
               System.out.println("TOO HIGH");
               continue;
           }
           catch(Exception e){
              
           }
       }
   }

}
class TooLow extends Exception{
  
   public TooLow(String s) {
       super(s);
   }
}

class TooHigh extends Exception{
  
   public TooHigh(String s) {
       super(s);
   }
}


//=============output=============

Enter your guess:
5
TOO LOW
Enter your guess:
7
TOO LOW
Enter your guess:
444
TOO HIGH