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
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.