如何在Java中关闭扫描仪?

问题描述:

每当我运行以下代码时,

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;
}

我收到此错误:

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)

我发现这与input_scanner.close();行有关,但是当我删除它时,我得到警告说:

I figured out it was something to do with the line input_scanner.close(); but when I remove it, I get warnings saying:

资源泄漏:"input_scanner"从未关闭"

Resource leak: "input_scanner" is never closed"

反正我可以阻止错误的发生并摆脱警告吗?

Is there anyway I can stop the errors from happening and get rid of the warnings?

您应该使用hasNextLine api检查是否有要扫描的数据供您使用:

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();
}