Exception handling infinite loop

前端 未结 1 855
醉酒成梦
醉酒成梦 2020-12-04 03:41

my question is short and sweet. I do not understand why my program infinitely loops when catching an error. I made a fresh try-catch statement but it looped and even copied

相关标签:
1条回答
  • 2020-12-04 04:27

    Your program runs forever because calling nextInt without changing the state of the scanner is going to cause an exception again and again: if the user did not enter an int, calling keyboard.nextInt() will not change what the scanner is looking at, so when you call keyboard.nextInt() in the next iteration, you'll get an exception.

    You need to add some code to read the garbage the user entered after servicing an exception to fix this problem:

    try {
         ...
    } catch(Exception e) {
        System.out.println("Error: invalid input:" + e.getMessage());
        again = true;
        keyboard.next(); // Ignore whatever is entered
    }
    

    Note: you do not need to rely on exceptions in this situation: rather than calling nextInt(), you could call hasNextInt(), and check if the scanner is looking at an integer or not.

    0 讨论(0)
提交回复
热议问题