+ 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 Respuestas
+ 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