Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please help! I\'m completely stuck on this Java code. I know it has to do with t

ID: 3572411 • 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.

A CHANGE TO MY CODE WOULD BE VERY MUCH APPRECIATED.

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

The reason might be
1)
use an if statement
if(keyboard.hasNext())
   keyboard.next();

if the buffer has not elements then it would through NoSuchElementException

2)
If the scanner is closed, it would close the input source(System.in),
but the scanner might be still open.
close the scanner at the end of the program.