javanetbeans-7

InputMismatchException for guess number


I am doing a guessing game where in I can input 1-100 but I am having a trouble in only accepting numbers if I typed a letter when I first run the program it will give me error and execute the program instantly image herebut if ityped number after I start the program and type letter next it give me a wrong message it should only display message saying "invalid input".image here Any suggestion thanks.

  package m1;
  import java.util.InputMismatchException;
   import java.util.Scanner;


  public class M1{


public static void main(String[] args) {

    Scanner Scanner = new Scanner(System.in);

    int between = 100;
    int secretNumber = (int)(Math.random()*between);
    int inputNum = 0;
    int guesses = 0;

    System.out.println("Please enter your guess: ");
    inputNum = Scanner.nextInt();
    guesses++;


    while (inputNum != secretNumber) {  

        try {

        // number too high or too low
        if (inputNum > 100 || inputNum < 1) {
            System.out.println("Out of Range!");
            System.out.println("Enter a guess between 1 and " + between + ".");
            inputNum = Scanner.nextInt();
        }

        // less than secretNumber
        if (inputNum < secretNumber) {
            System.out.println("Too Low...Try Again!");
            inputNum = Scanner.nextInt();
            guesses++;
        }

        // greater than secretNumber
      if (inputNum > secretNumber) {
        System.out.println("Too High...Try Again!");
        inputNum = Scanner.nextInt();
        guesses++;
    }
    }
    catch(InputMismatchException e){
        System.out.println("Invalid Input");
        Scanner.next();

    }
    }


    System.out.println("\nWell done! The secret number was " + secretNumber + "." + "\nYou took " + guesses +  " guesses.");
    }

}


Solution

  • Try the below code:

    import java.util.Scanner;
    import java.util.concurrent.ThreadLocalRandom;
    
    class Main {
        private static final String GUESS_PROMPT_PATTERN = "Please enter a guess between %d and %d inclusive: ";
        private static final String WIN_PROMPT_PATTERN = "Well done! The secret number was %d. You took %d guesses.\n";
    
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int minimumGuess = 1, maximumGuess = 100;
            int secretNumber = ThreadLocalRandom.current().nextInt(minimumGuess, maximumGuess + 1);
            int guesses = 0;
            String guessPrompt = String.format(GUESS_PROMPT_PATTERN, minimumGuess, maximumGuess);
            System.out.println("Lec's Guessing Game");
            System.out.println("====================");
            System.out.print(guessPrompt);
            while (scanner.hasNext()) {
                if (scanner.hasNextInt()) {
                    guesses++;
                    int inputNum = scanner.nextInt();
                    if (inputNum == secretNumber) {
                        break;
                    }
                    // Input number too high or too low.
                    if (inputNum > maximumGuess || inputNum < minimumGuess) {
                        System.out.println("Out of Range!");
                        scanner.nextLine();
                        System.out.print(guessPrompt);
                    }
                    // Input number was less than the secret number.
                    else if (inputNum < secretNumber) {
                        System.out.println("Too Low... Try Again!");
                        System.out.print(guessPrompt);
                    }
                    // Input number was greater than the secret number.
                    else {
                        System.out.println("Too High... Try Again!");
                        System.out.print(guessPrompt);
                    }
                } else {
                    System.out.print("ERROR: Invalid Input");
                    System.out.print("Please enter a number: ");
                    scanner.next();
                }
            }
            System.out.printf(WIN_PROMPT_PATTERN, secretNumber, guesses);
        }
    }