+ 1
Using java scanner in else if
It works if you enter 1, but not for anything else. What should I do? https://code.sololearn.com/cSxqDGaDmA5K/?ref=app
2 Answers
+ 2
Iâm unfamiliar with using Scanners but I read that NoSuchElementExceptions are thrown if the scanner is exhausted/overused
Youâre using an if-else statement where ch.nextInt() is called more than once if it fails the first if condition
Extract this out into its own variable
e.g. int x = ch.nextInt()
and if else on x so the scanner isnât trying to call nextInt more than once
0
*Iâll further add why to explicitly explain what happened:
Say you enter â2â
if(ch.nextInt()) fails and â2â is read
else if (ch.nextInt() ... ) canât be processed as â2â has already been read and there is no more input to read from the scanner hence an exception