try/catch with InputMismatchException creates infinite loop

前端 未结 7 1031
醉话见心
醉话见心 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 13:46

    As the bError = false statement is never reached in the try block, and the statement is struck to the input taken, it keeps printing the error in infinite loop.

    Try using it this way by using hasNextInt()

    catch (Exception e) {
                System.out.println("Error!");
               input.hasNextInt();         
            }
    

    Or try using nextLine() coupled with Integer.parseInt() for taking input....

    Scanner scan = new Scanner(System.in);
    
    int num1 = Integer.parseInt(scan.nextLine());
    int num2 = Integer.parseInt(scan.nextLine());
    

提交回复
热议问题