-2

I am needing to stop the user from entering a string value.

Here is what I've tried so far.

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

public class guessinggame
{
    public static void main (String[] args)
    {
        int randomNumber = new Random().nextInt(10);
        System.out.println("My number is " + randomNumber + ". ");

        System.out.println("I’m thinking of a number between 0 and 9.");
        System.out.println("What is your guess:");


        Scanner keyboard = new Scanner(System.in);
        int guess = keyboard.nextInt();
        guess1(guess);


        int input = 0;


            try{
                input = keyboard.nextInt();

            }catch (InputMismatchException e){
                int guess = keyboard.nextInt();
                System.out.println("Invalid.");
            }



           if (guess < randomNumber) {
                System.out.print("your guess was too low.");
           }else if (guess > randomNumber){
                System.out.print("your guess was too high.");
            }else if (guess == randomNumber){
                System.out.print("your guess was correct.");
        }
    }
}

The error I am receiving is: Duplicate local variable guess preventing program from compiling, however I imagine I am also missing bits from making this program do what I want it to.

It needs to only accept integer values as input between 0-9. Anything else (including strings) should return as invalid.

sawreals
  • 338
  • 4
  • 15
  • 5
    READ THE ERROR!!!! The compiler doesn't spit these things out for fun you know. They are important. And if your code doesn't compile how do you know the try-catch doesn't work - i.e. your question title is VERY BAD! – John3136 Sep 27 '16 at 00:38
  • It doesn't work because I also get a run-time error which says Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:864) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.nextInt(Scanner.java:2117) at java.util.Scanner.nextInt(Scanner.java:2076) at guessinggame.main(guessinggame.java:17) – sawreals Sep 27 '16 at 03:08
  • @sawreals2: If you can show your updated code and indicate which line is throwing the exception, the community can continue to assist if you're still facing a problem. – David Sep 27 '16 at 12:36
  • @David I've updated the code. The mismatcherror is on line 17. I tried changing int guess to guess as Eric suggested but this gave an error which states it cannot be resolved to a variable. The program detects the mismatch error, but I want it to print out "invalid" instead, as I have written in the catch block. – sawreals Sep 27 '16 at 18:17
  • @sawreals2: The answer below was suggesting that you remove the `int` keyword from your *second* declaration of that variable, not the first one. Clearly a variable needs to be declared before it can be used. As for the exception you're getting, what are you providing as input to the program when it runs? If the input can't be parsed to an `int` then `nextInt()` is going to throw an exception. You'd wrap it in a `try/catch` block to handle that exception. – David Sep 27 '16 at 18:22
  • @David that's what I assumed, as you can see I changed int guess to guess on line 28. For input I enter any string, "abc" for example. – sawreals Sep 27 '16 at 18:30
  • @sawreals2: "abc" can't be parsed to an integer. That's why it's throwing an exception. – David Sep 27 '16 at 18:43
  • @David can I put guess = Integer.parseInt(); in the catch block? – sawreals Sep 27 '16 at 18:48
  • @David, the exception is ok, but is there anyway to just print out invalid? The program is realizing the incorrect input type, I just want it to print something out when that happens. No need for re-entry of input. – sawreals Sep 27 '16 at 18:50
  • @sawreals2: You can put whatever you want in the `catch` block, it depends on how you want to handle the error. It sounds like you want to print something out in the catch block, so you'd put a print statement in there. – David Sep 27 '16 at 18:54
  • I do have a print statement in my catch block --> System.out.println("Invalid."); – sawreals Sep 27 '16 at 18:56
  • @sawreals2: Then what's the problem? What isn't working? How have you modified the code from the original question above and in what way are those modifications not producing the desired result? – David Sep 27 '16 at 19:02
  • @sawreals2: Note that the edits you've made to the question since you originally asked it have invalidated the description of the problem and invalidated the correct and helpful answers below. This is generally considered poor form on Stack Overflow and leads to confusion. If a question significantly changes after it has been answered, it often merits asking a new one. When changing information in a question, be sure not to invalidate other information which is still in the question. Otherwise nobody will be able to figure out which information is accurate. – David Sep 27 '16 at 19:15
  • @David I have modified the original question to contain the original revision of the question from yesterday as to not cause confusion. Additionally, please note that the modifications I made were changing `int guess` to `guess` on line 28. It still is not printing `invalid` despite there being the print statement in the catch block, to catch string input entry. – sawreals Sep 27 '16 at 21:33
  • @sawreals2: In that case the original question, as posted, has been answered. The code in the question won't print anything because it won't compile. The error which prevents it from compiling is described and corrected in the answers below. If you have different code which is producing a different error then that likely merits a different question. We'd need to see the current version of the code and information about the current error in order to help. If I were to *guess*, you're getting an exception *before* you even enter your `try` block, making the `catch` block irrelevant. – David Sep 27 '16 at 21:42

3 Answers3

1

The compiler is giving you the error because you have declared guess twice:

  • Once at the beginning with int guess = keyboard.nextInt();
  • Then in the catch clause with int guess = keyboard.nextInt(); again

Also note that you readInt() several times in your code, meaning that you are trying to get user input several times. You should reference guess in your code instead.

If you are often having trouble with compile errors and such, you may want to use an IDE such as Eclipse.

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
1

The main error is that you are re-declaring guess in the catch block.

What you really need to do is loop around if invalid data is input

int guess = -1;  // some magic number
while (guess <= -1) {  // we do not want negative number
    try{
            guess = keyboard.nextInt();
        }catch (InputMismatchException e){
            System.out.println("Invalid - try again.");
            continue;
        }

    if (guess >= 0) {
        break;
    }
    System.out.println("We want between 0 and 9 - try again.");
}

// now we have valid value for guess

Edit

As per new requirements

   int guess = -1;  // some magic number
    try{
            guess = keyboard.nextInt();
        }catch (InputMismatchException e){
            // do not need to do anything
        }

    if (guess < 0) {
            System.out.println("Invalid - will exit.");
            System.exit(-1); 
    }
// now we have valid value for guess
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0
int guess = keyboard.nextInt();

should just be

guess = keyboard.nextInt();
Eric Bachhuber
  • 3,872
  • 2
  • 19
  • 26
  • additionally, I cannot change it to just guess, it cannot be resolved to a variable in that case, and creates more errors throughout the code. – sawreals Sep 27 '16 at 03:48