try/catch with InputMismatchException creates infinite loop

前端 未结 7 903
醉话见心
醉话见心 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:08

    @Limp, your answer is right, just use .nextLine() while reading the input. Sample code:

        do {
            try {
                System.out.println("Enter first num: ");
                n1 = Integer.parseInt(input.nextLine());
                System.out.println("Enter second num: ");
                n2 = Integer.parseInt(input.nextLine());
                nQuotient = n1 / n2;
                bError = false;
            } catch (Exception e) {
                System.out.println("Error!");
            }
        } while (bError);
    
        System.out.printf("%d/%d = %d", n1, n2, nQuotient);
    

    Read the description of why this problem was caused in the link below. Look for the answer I posted for the detail in this thread. Java Homework user input issue

    Ok, I will briefly describe it. When you read input using nextInt(), you just read the number part but the ENDLINE character was still on the stream. That was the main cause. Now look at the code above, all I did is read the whole line and parse it , it still throws the exception and work the way you were expecting it to work. Rest of your code works fine.

提交回复
热议问题