Please help! I\'m completely stuck on this Java code. I know it has to do with t
ID: 3571828 • Letter: P
Question
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 but on a mobile device (Sololearn.com) 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! Please 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)
Explanation / Answer
This error occurs when calling next you should check if scanner has one.
if(scan.hasNext())
scan.next();
there is no problem with
int theNum = keyboard.nextInt( );
check it out.