如何在Java中关闭扫描仪? [英] How do I close a scanner in java?
本文介绍了如何在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();
}
这篇关于如何在Java中关闭扫描仪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文