try/catch with InputMismatchException creates infinite loop

前端 未结 7 1010
醉话见心
醉话见心 2020-11-22 13:27

So I\'m building a program which takes ints from user input. I have what seems to be a very straightforward try/catch block which, if the user doesn\'t enter an int, should

7条回答
  •  梦谈多话
    2020-11-22 14:06

    To complement the AmitD answer:

    Just copy/pasted your program and had this output:

    Error!
    Enter first num: 
    .... infinite times ....
    

    As you can see, the instruction:

    n1 = input.nextInt();
    

    Is continuously throwing the Exception when your double number is entered, and that's because your stream is not cleared. To fix it, follow the AmitD answer.

提交回复
热议问题