0

I am executing the below code to read a string from the input stream with the scanner object.

   public class Test{
    public static void main(String[] args) {
        String userInput1 = getUserInput();
        System.out.println(userInput1);
        String userInput2 = getUserInput();
        System.out.println(userInput2);     
    }

private static String getUserInput() {
        System.out.println("Enter the String");
        Scanner scanner = new java.util.Scanner(System.in);
        String input = scanner.next();
        scanner.close();
        return input;
    }
}

The first invocation to the method getUserInput succeeded without any issues.But he second invocaton threw NoSuchElementException.

Enter the String
test1
test1
Enter the String
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1371)
aniugne
  • 67
  • 4

1 Answers1

0

There are two problems with the code

  1. It assumes that there already has been input. A simple while(!scanner.hasNext()){} before the locations where you call scanner.next(); should work.

  2. You are creating many scanners (this may or may not impact the code, but does impact efficiency) Instead, the Scanner scanner = new Scanner(System.in); can be broken up into a declaration (Scanner scanner;) outside a method and then defined (scanner = new Scanner(System.in);) in the main method or initialization code.

Daniel M.
  • 1,433
  • 13
  • 24
  • Calling `hasNext` and `next` on `System.in` has the same effect: these calls block the thread until there is a token to read. So there is no point in using that `while` loop. – Tom Jun 20 '15 at 13:48
  • @Tom But you can use it for input type checking ("please enter a number" when someone types a string) – Daniel M. Jun 20 '15 at 13:52
  • So, somthing like `System.out.print("enter number: "); while(!scanner.hasNextInt()){}`? This is a bad idea for type checking. You might want to try it, to find out why. – Tom Jun 20 '15 at 13:56
  • No: more like `System.out.print("enter number: "); while(!scanner.hasNextInt()){ System.out.println(/*Some message*/); scanner.next(); } result = scanner.nextInt();` – Daniel M. Jun 20 '15 at 14:01