Using java scanner in else if | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

22nd Mar 2019, 6:39 AM
Arun Sharma
Arun Sharma - avatar
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
22nd Mar 2019, 6:50 AM
Jenine
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
22nd Mar 2019, 7:20 AM
Jenine