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?



Read more here: https://stackoverflow.com/questions/67938586/how-to-prevent-wrong-user-input-on-a-variable

Content Attribution

This content was originally published by Agustin at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: