Exception handling with a do-while loop in Java

后端 未结 5 692
孤街浪徒
孤街浪徒 2021-01-23 12:43

The algorithm should take in 3 integers to an ArrayList. If the input is not an integer, then there should be a prompt. When I execute my code the catch clause is e

5条回答
  •  不要未来只要你来
    2021-01-23 13:22

    If inputNum = input.nextInt(); cannot be fit into an int and a InputMismatchException is raised, the input of the Scanner is not consumed.

    So after the catch, it loops and it goes again here :

    inputNum = input.nextInt();
    

    with exactly the same content in the input.

    So you should execute input.nextLine(); in the catch statement to discard the current input and allow a new input from the user.
    Besides it makes more sense to catch InputMismatchException rather than Exception as other exception with no relation with a mismatch could occur and it would not be useful to display to the user "invalid number " if it is not the issue :

        catch (InputMismatchException e){
            System.out.println("invalid number ");
            input.nextLine();
        }
    

提交回复
热议问题