Question: I have to write a guessing game Java program using exceptions. The program generates a random number and the user must guess the number. Here

I have to write a guessing game Java program using exceptions. The program generates a random number and the user must guess the number. Here are the requirements:

-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.

Here is my code:

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package brown_unit3; import java.util.Random; import java.util.Scanner; /** * * @author krbrown */ public class Brown_Unit3 {

/** * @param args the command line arguments */ public static void main(String[] args) { Random num = new Random(); Scanner scan = new Scanner(System.in); int guessNum = num.nextInt(100); int guess; boolean win = false; while (win == false){ System.out.println("Welcome to Kristin's Guessing Game! Please guess a number between 1 & 100."); guess = scan.nextInt(); try{ if (guess == guessNum){ win = true;} else if (guess< guessNum){ throw new TooLow("The number you guessed is too low. Please try again."); } else if (guess> guessNum){ throw new TooHigh("The number you guess is TOO HIGH. Please try again."); } } catch(TooLow e){ System.out.println(e.getMessage()); } catch(TooHigh e){ System.out.println(e); } } System.out.println("Congratulations, you guessed correctly!"); } }

TooHigh.java

public class TooHigh extends Exception{ String errorMsg ; public TooHigh(String s){ this.errorMsg = s; } public String toString(){ return (errorMsg ) ; } }

TooLow.java

public class TooLow extends Exception{ String errorMsg ; public TooLow(String s){ this.errorMsg = s; } public String toString(){ return (errorMsg ) ; } }

When the code is generated, the first entrance displays correctly. However, when the user tries inputing another number, the program displays "null"

What am I doing wrong?

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!