That one i found it the hard way so i put it here for others to take vision and possibly avoid
Assume you call that method from some other method in your project where you had setup a Scanner object for user's input
Method's logic is simple iterate on input's stream till you get a valid integer. In case of invalid user's input i.e. when nextInt() can’t convert input's
string to an integer,
throw an InputMismatchException
What you get if you run the following method's code? an infinite loop right? but why? ...
... because from
API documentation
...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...
So got you the trick?
nextInt() was leaving the invalid user input into the stream(I instead thought had to move on) and after catch's return in subsequent while's iterations nextInt() clearly read the same invalid character(and not the fresh one that should be provided by the user in the new iteration) throw his exception(ever leaving the same invalid user input into stream) and so on ad infinitum.
Ok found the culprit how to resolve?
It's trivially enough a sc.next() between lines 6 and 7; that consume(gets rid) the invalid character and so now nextInt() can read correctly the fresh user's input