Infinite While Loop When InputMidmatchException is caught in try-catch block [duplicate]

[亡魂溺海] 提交于 2019-11-29 15:11:25

No the scanner is not skipped, it's just starting at the beginning of the input. From the JavaDoc:

If the translation is successful, the scanner advances past the input that matched.

This means if the conversion isn't successfull the scanner won't advance. You'd thus have to manually skip the incorrect input using just next().

Edit: you might want to check for hasNextInt() before trying to read the input.

you loop while continueVar is true, but you never set to to false, so the loop never exits.

I think you want to set continueVar to false in the exception handler.

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

The token that caused the mismatch is still in the scanner's buffer. You need to clear it before trying to scan again.

You can do that by calling next() in your catch block, like this:

catch (InputMismatchException i) {
    System.out.println("What the f***?");
     sc.next();           
}

Also, you don't need to set continueVar to true again. You never set it to false, so it will stay true. Guessing that's an artifact of you removing this into a mini program.

Scanner does not advance when bad token is found. Look at Scanner.java, lines 2095-2096:

catch (NumberFormatException nfe) {
    position = matcher.start(); // don't skip bad token
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!