I know there are a lot of questions about this exception on Stack Overflow but I can't find an answer or an explanation about my particular issue.
I have two functions from two different classes. The first one uses the second one.
The purpose of this code is only to illustrate the problem and it is not my real code.
// ClassOne.java
public void function1() {
Scanner input = new Scanner(System.in);
ClassTwo.function2();
String inputValue = input.nextLine(); // throws NoSuchElementException
input.close();
}
// ClassTwo.java
public void function2() {
Scanner input = new Scanner(System.in);
String inputValue = input.nextLine();
input.close();
}
If I do not call function2 inside function1, everything works fine.
But if I do, I got the exception java.util.NoSuchElementException: No line found
.
The exception is thrown from the String inputValue = input.nextLine();
line of the first function.
If I do not close the Scanner in the second function, then everything works fine again.
Somehow it seems that closing the second scanner affects the first one (I assume that is because they both scan System.in).
I want to close the second scanner because otherwise I got a warning and I don't like them (reveals poor code).
Using Scanner.hasNextLine()
does not save me here as a Scanner on System.in is supposed to wait for the user to enter a new line.
So my question is why is this happening, and how to fix it ?