1

Hi I'm currently having trouble throwing exceptions on my guessing game code. I want to put an exception for string input (instead of int) and also an exception for entering a number beyond the limit(50). Thanks.

public static void main (String[] args)

{
    Random ran = new Random();
    int numberToGuess = ran.nextInt(50)+1;
    int numberOfTries = 0;
    Scanner input = new Scanner (System.in);
    int guess;
    boolean win = false;

    while (win == false)
    {
        System.out.println("Guess a number from 1 to 50!");
        guess = input.nextInt();
        numberOfTries++;

        if (guess == numberToGuess)
        {
            win = true;
        }
        else if (guess < numberToGuess)
        {
            System.out.println("Too low. Try again.");
        }
        else if (guess > numberToGuess)
        {
            System.out.println("Too high. Try again.");
        }
    }

    System.out.println("You got it in " + numberOfTries + " attempt(s)!");

}
steveee26
  • 27
  • 3
  • what is the stack trace? – Jason V Jul 31 '17 at 15:32
  • What is the trouble? – Compass Jul 31 '17 at 15:33
  • 1
    @Jason The OP isn't getting an exception, they're asking how to throw one. – azurefrog Jul 31 '17 at 15:33
  • What do you want to achieve with the exceptions? – Robin Topper Jul 31 '17 at 15:33
  • 2
    This is kind of related: [Validating input using java.util.Scanner](https://stackoverflow.com/questions/3059333/validating-input-using-java-util-scanner) – Tom Jul 31 '17 at 15:34
  • AH, i see. i guess i rushed through the question. – Jason V Jul 31 '17 at 15:34
  • How should I put an exception for entering a string instead of int? – steveee26 Jul 31 '17 at 15:34
  • entering a non numeric string where integer is expected would result in an exception so use try catch block to catch InputMismatchException to display appropriate error message and for the other case i.e. number being greater than 50, you can simply display an error message using if else block – digidude Jul 31 '17 at 15:35
  • [How to throw a general Exception in Java](https://stackoverflow.com/questions/6942624/how-to-throw-a-general-exception-in-java) – azurefrog Jul 31 '17 at 15:36
  • I tried to put a try catch block but it doesnt seemed to work. Also, the if-else block for the >50 exception creates confusion with the 'else if (guess > numberToGuess)' part – steveee26 Jul 31 '17 at 15:38
  • for e.g. try {guess = input.nextInt(); } catch (InputMismatchException ime) {System.out.println("Invalid Input"); } catch (Exception e) { Syste.out.println("Error log : "+e);} should help – digidude Jul 31 '17 at 15:39
  • still won't work :( – steveee26 Jul 31 '17 at 15:53

2 Answers2

0

Here is a potential solution:

import org.apache.commons.lang3.StringUtils;

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

public class StackOverflow45419907 {
  private final Scanner input;
  final int numberToGuess;

  public StackOverflow45419907() {
    this.input = new Scanner(System.in);
    numberToGuess = new Random().nextInt(50) + 1;
  }

  public static void main(String[] args) {
    new StackOverflow45419907().playGame();
  }

  private void playGame() {
    int numberOfTries = 0;
    int guess = -1;

    while (guess != numberToGuess) {
      guess = collectGuess();
      numberOfTries++;

      printClue(guess);
    }
    System.out.println("You got it in " + numberOfTries + " attempt(s)!");
  }

  private void printClue(int guess) {
    if (guess < numberToGuess) {
      System.out.println("Too low. Try again.");
    } else if (guess > numberToGuess) {
      System.out.println("Too high. Try again.");
    }
  }

  private int collectGuess() {
    System.out.println("Guess a number from 1 to 50!");
    final String potentialGuess = input.nextLine();
    return validateAndParse(potentialGuess);
  }

  private int validateAndParse(String potentialGuess) {
    if (!StringUtils.isNumeric(potentialGuess)) {
      throw new IllegalArgumentException("not numeric: " + potentialGuess);
    }
    final int asInt = Integer.parseInt(potentialGuess);
    if (asInt > 50 || asInt < 1) {
      throw new IllegalArgumentException("value out of valid range: " + asInt);
    }
    return asInt;
  }
}
Andreas
  • 4,410
  • 2
  • 19
  • 28
-1

I don't really think you need to throw exception. you can use Scanner#hasNextInt() to validate the input is integer. then assign it to the guess variable and just check if its bigger then 50.

If you really what to throw exception. use throw new RuntimeException(message) if the input is not an integer or it is larger than 50.

Edit: I wont use it like that, but I believe you just want to know about the exceptions.

System.out.println("Guess a number from 1 to 50!");
numberOfTries++;
if (!input.hasNextInt())
     throw new IllegalArgumentException("Input must be a number");

guess = input.nextInt();
if (guess < 1 || guess > 50)
     throw new IllegalArgumentException("Input must be a number from 1 to 50");
  • On what of the code shoud I put those? Sorry I'm a noob in java programming – steveee26 Jul 31 '17 at 15:52
  • Don't throw a raw `RuntimeException`, use a subclass; `IllegalArgumentException` sounds about right. – Andreas Jul 31 '17 at 16:08
  • It's not a good practice to throw top class exceptions. More specific exception can improve documentation and more clearly describe to client why it's occurred. Furthermore, `RuntimeException` means unrecoverable state, I don't see any unrecoverable state in the original question – J-Alex Jul 31 '17 at 16:08