+ 4

Need help with a Java exception error

Please help! I'm completely stuck on this Java code. I know it has to do with the nextInt() but not sure how to fix it. It runs on my desktop at Sololearn.com but on a mobile device I get the following error (Why could this be?): java,util.NoSuchElementException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at Inspiration.main(Inspiration.java:43) BELOW IS MY JAVA CODE: import java.util.Scanner; import java.util.Random; import static java.lang.Math.*; public class Inspiration { private int theNum; public Inspiration( int num ) { theNum = num; } public void setTheNum( int num ) { theNum = num; } public int getTheNum( ) { return theNum; } public static void main( String[] args ) { try { Scanner keyboard = new Scanner( System.in ); /* System.out.print ( "Pick a number from 1 to 20: " ); */ int theNum = keyboard.nextInt( ); /* this user input assures that the final number is atleast one. */ Inspiration i = new Inspiration( theNum ); if (i.isValid( )) { i.serendipidy(); i.inspirationMachine(); } else { System.out.println("Invalid user input!\nPlease enter an integer from 1 to 20."); } } catch (Exception e) { e.printStackTrace(); // System.out.println("An error occurred"); } //OTHER METHODS ARE BELOW THIS (NOT INCLUDED)

4th Dec 2016, 1:32 AM
bernscode
bernscode - avatar
2 Antworten
+ 4
I figured it out! Removed the catch block, but the program is still robust enough to deal with improper user input. Check it out... The Inspiration Machine! *Please leave a like on this answer if you've ever stayed up late working on a bug in your code. -bErN
7th Dec 2016, 9:47 AM
bernscode
bernscode - avatar
+ 1
This happens since on mobile you have to enter all your commands in each one on its own line after pressing run, if your program is still waiting for input after each line entered has been executed then you will receive that exception
4th Dec 2016, 11:37 PM
kostyantin2216
kostyantin2216 - avatar