When ever I run the following code,
private static String input(String Message){
Scanner input_scanner = new Scanner(System.in);
System.out.print("\n" + Message);
String string = input_scanner.nextLine();
input_scanner.close();
return string;
}
I get this error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at main.learn.input(learn.java:25)
at main.learn.main(learn.java:13)
I figured out it was something to do with the line input_scanner.close(); but when I remove it, I get warnings saying:
Resource leak: "input_scanner" is never closed"
Is there anyway I can stop the errors from happening and get rid of the warnings?
解决方案
You should check if you have data to consume for Scanner using hasNextLine api which you could do like:
String string = "";
if (input_scanner.hasNextLine()) {
string = input_scanner.nextLine();
}