Reputation: 1274
I'm writing a game in java, and I have a method that asks user to input the value from Console:
public String getUserInput() {
try (Scanner scan = new Scanner(System.in)) {
String s = scan.nextLine();
return s;
}
}
The thing is I want to invoke this method various number of times depends on external parameters and I never know in advance, will I invoke again or not.
But when I invoke methods like this for the second call - I get
Exception in thread "main" java.util.NoSuchElementException: No line found
Problems:
Upvotes: 0
Views: 152
Reputation: 73528
Don't reopen or recreate it. Use one Scanner
for the duration of your program.
Closing a Scanner
(as in this case, with your try-with-resources
block) will close its input, in this case System.in
. You don't want to close that, since you can't reopen it.
Upvotes: 5