chritschl
chritschl

Reputation: 33

Java - String Input Exception Handling

I´m totally new to Java and I´m stuck. I have to create the game "guess the Number". I´m able to do the most parts but I´m don´t now how to handle the User Input if its a String. I want to be able to tell the User that the Input was not correct if he enters a String, and repeatedly ask for Input. It would be great if someone could help me here :)
Here is my Code:

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

public class SWENGB_HW_2 {

public static void main(String[] args) {

    System.out.println("Welcome to the guess the number game!\n");
    System.out.println("Please specify the configuration of the game:\n");

    Scanner input = new Scanner(System.in);

    System.out.println("Range start number (inclusively):");
    int startRange;
    startRange = input.nextInt();

    System.out.println("Range end (inclusively):");
    int endRange;
    endRange = input.nextInt();

    System.out.println("Maximum number of attemps:");
    int maxAttemp;
    maxAttemp = input.nextInt();

    System.out.println("Your Task is to guess the random number between "
            + startRange + " and " + endRange);

    Random randGenerator = new Random();
    int randNumber = randGenerator.nextInt((endRange - startRange) + 1)
            + startRange;
    int numberOfTries = 0;

    System.out
            .println("You may exit the game by typing; exit - you may now start to guess:");
    String exit;
    exit = input.nextLine();


    for (numberOfTries = 0; numberOfTries <= maxAttemp - 1; numberOfTries++) {

        int guess;
        guess = input.nextInt();



        if (guess == randNumber) {
            System.out.println("Congratz - you have made it!!");
            System.out.println("Goodbye");
        } else if (guess > randNumber) {
            System.out.println("The number is smaller");
        } else if (guess < randNumber) {
            System.out.println("The number is higher");
        }

    }
    if (numberOfTries >= maxAttemp) {
        System.out.println("You reached the max Number of attempts :-/");
    }

}
}

Upvotes: 1

Views: 5888

Answers (2)

aioobe
aioobe

Reputation: 420951

You can create a utility method that looks like this:

public static int nextValidInt(Scanner s) {
    while (!s.hasNextInt())
        System.out.println(s.next() + " is not a valid number. Try again:");
    return s.nextInt();
}

and then, instead of

startRange = input.nextInt()

you do

startRange = nextValidInt(input);

If you want to deal with the "exit" alternative, I'd recommend something like this:

public static int getInt(Scanner s) throws EOFException {
    while (true) {
        if (s.hasNextInt())
            return s.nextInt();
        String next = s.next();
        if (next.equals("exit"))
            throw new EOFException();
        System.out.println(next + " is not a valid number. Try again:");
    }
}

and then wrap the whole program in

    try {
        ...
        ...
        ...
    } catch (EOFException e) {
        // User typed "exit"
        System.out.println("Bye!");
    }
} // End of main.

Btw, the rest of your code looks great. I've tried it and it works like a charm :-)

Upvotes: 3

Elliott Frisch
Elliott Frisch

Reputation: 201419

You could check that the scanner has an int before you attempt to read it. You can do that by calling hasNextInt() with something like

while (input.hasNext() && !input.hasNextInt()) {
  System.out.printf("Please enter an int, %s is not an int%n", input.next());
}
int startRange = input.nextInt();

Upvotes: 1

Related Questions