javainputmismatchexception

How to prevent wrong user input on a variable?


Im currently trying to build a code that prevents wrong user input (storing a char/string to a integer, e.g.) but Im not being able to make it to work...

    public static void main(String[] args) {
    int num=0, option=0;
    boolean keep=true;
    
    Scanner scan = new Scanner(System.in);
    
    while(keep) {
        System.out.println("1 - Test Exception.");
        System.out.println("2 - Out.");
        
        option = scan.nextInt();
        switch(option) {
        
        case 1:
            System.out.println("Write a number: ");
            if(scan.hasNextInt()) {
                num = scan.nextInt();
            }
            else {
                System.out.println("Wrong input...");
            }
            break;
        case 2:
            keep=false;
            System.out.println("Bye !");
            break;
        }
        
    }

}

As soon as I input a char/string, the code stops working. The exception occurs in the line option = scan.nextInt();

What am I missing?


Solution

  • You expect that the user enters an int, however, the user is free to enter whatever the user pleases. Therefore you need to ensure that the input can be parsed.

    String userInput = scan.next(); //scan the input
    int value;
    try {
        value = Integer.parseInt(userInput); // try to parse the "number" to int
    } catch (NumberFormatException e) {
        System.out.println("Hey, you entered something wrong...");
        // now you can ask the user again to enter something
    }