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)