[Solved] Improving my guessing game [closed]


one of 2 things could be done here either replacing the exception throwing with something else which would be something like this:

inside Game.main() change this:

try{
    jar.guess();

} catch(IllegalArgumentException iae){
    System.out.println("Please choose a valid number");
}

to this:

jar.guess();

simply eliminating the try catch check and inside Jar.guess() change this:

if(guess>maxNumberOfItems){
    throw new IllegalArgumentException();
} else if (guess<1){
    throw new IllegalArgumentException();
}

to this:

// the || means logical OR, if either of the 2 conditions is true than the if will read true in this case

if(guess>maxNumberOfItems || guess<1){
    System.out.println("Please choose a valid number");
}

however if you’re using exceptions to learn exceptions than the reason you are having the issue is because of 2 things
first off – when the exception occurs in guess() but isn’t caught java’s exception system checks to see if guess() expects to be throwing exceptions which in your case it doesn’t, which means the exception never leaves guess() and the exception errors out and your try catch never sees the exception.
The way you tell a method to pass along any exceptions of a certain type is to put the keyword throws followed by the types of exceptions it should pass along between the () and the opening { of the method head like this:

public void guess() throws IllegalArgumentException {

but that only allows your current try catch to see the exception and stops the program from erroring out

in order to get it to keep prompting for guesses over and over the try catch in this case has to be inside the while loop that causes the repeated guessing in the first place. To do this you can either put the try catch in guess()

while(guess != numberOfItems){
    try{
        if(guess>maxNumberOfItems){
            throw new IllegalArgumentException();
        } else if (guess<1){
            throw new IllegalArgumentException();
        }
    } catch(IllegalArgumentException iae){
        System.out.println("Please choose a valid number");
    }

    prompter.tryAgain();
    guess = scanner.nextInt();
    numberOfGuesses++;
}

or you can add the throws IllegalArgumentException clause to guess() and move the while loop (and some of the variables that store things like number of guesses) outside of guess() to have guess() called once for each guess instead of once per game

for more info about the throws clause check oracle’s java documentation here

solved Improving my guessing game [closed]