1

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 :-/");
    }

}
}
2
  • possible duplicate of Understanding try & catch and error handling Commented Oct 9, 2014 at 13:14
  • You probably want to add break; after printing Goodbye to exit the for-loop and terminate the program. Commented Oct 9, 2014 at 13:31

2 Answers 2

3

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 :-)

Sign up to request clarification or add additional context in comments.

5 Comments

Thx thats nice to hear :)
I have one more question. What do you mean with "warp the whole program in it"? Which parts of the code?
Put try { as the very first thing after main(String[] args) { and } catch (EOFException e) { System.out.println("Bye"); } before the closing } of main. By throwing EOFException anywhere in main, you would end up in the catch-block and then terminate directly.
Unfortunately thats not possible, because a error occours by the catch block: "Unreachable catch block for EOFException. This exception is never thrown from the try statement body" - do you know how to fix this?
Presumably you didn't use the getInt(Scanner s) throws EOFException alternative I gave in my answer.
1

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.