1

I want to make a simple app that reads a string from the keyboard and prints it with a message afterwards. This is my code:

import java.util.Scanner; 

public class HelloWorld {   
    public static void main(String argv[]) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("enter an integer");
        int myint = keyboard.nextInt();
        System.out.println(myint+ " <- that's the string");     
    }    
}

Something is wrong because I get an error message:

Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:862) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.nextInt(Scanner.java:2117) at java.util.Scanner.nextInt(Scanner.java:2076) at HelloWorld.main(HelloWorld.java:25)

How can I solve this?

Morteza Jalambadani
  • 1,881
  • 5
  • 19
  • 30
Leo Messi
  • 2,544
  • 1
  • 21
  • 49

2 Answers2

1

You have to use scanner.hasNext() and scanner.hasNextInt().

  // find the next int token and print it
  // loop for the whole scanner
  while (scanner.hasNext()) {

     // if the next is a int, print "Found" and the int
     if (scanner.hasNextInt()) {
        System.out.println("Found " + scanner.nextInt());
     }
     // if no int is found, print "Not found" and the token
     System.out.println("Not found " + scanner.next());
  }
Tony Stark
  • 2,029
  • 1
  • 17
  • 34
1

NoSuchElementException will be thrown if no more tokens are available. This is caused by invoking nextInt() without checking if there's any integer available. To prevent it from happening, you may consider using hasNextInt() to check if any more tokens are available.

if( keyboard.hasNextInt() )
  int myint = keyboard.nextInt();

read at this link

The Scientific Method
  • 2,151
  • 2
  • 10
  • 21