Error handling reading ints from Scanner in while loop

后端 未结 1 1727
南笙
南笙 2021-01-21 12:24

I am try to catch an exception and get it to repeat, but it just creates an endless loop and then crashes the program... why is it doing this? Is it something wrong with my catc

相关标签:
1条回答
  • 2021-01-21 13:14

    It goes into an endless loop if you enter an invalid number because the invalid token is still left on the stream, and nextInt() keeps trying over and over again to grab it.

    You will have to get the data off the stream.

    One thing you could do is use nextLine() instead, then explicitly try and parse the returned String into an integer (e.g. with Integer.parseInt()).

    Another thing you could do is call input.next() (or input.nextLine()) in the exception handler, to read (and discard) the garbage input. You may have to tweak the Scanner delimiters to get next() to work for you if it's not meeting your requirements with default settings.

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