Java:尝试(扫描仪扫描=新的扫描仪(System.in){}导致异常 [英] Java: try(Scanner scan = new Scanner(System.in) { } causing an exception
问题描述
使用尝试(扫描仪扫描=新的扫描仪(System.in)){}
导致
线程main中的异常java.util.NoSuchElementException
Exception in thread "main" java.util.NoSuchElementException
当我尝试调试它时, p>
When I try to debug it says that
变量信息不可用,源编译时没有-g选项。
Variable information not available, source compiled without -g option.
并显示以下代码
public Scanner(InputStream source) {
this(new InputStreamReader(source), WHITESPACE_PATTERN);
}
我使用这一行的方法之一:
One of my methods that uses this line:
protected String loginName(){
String username;
String password;
try (Scanner scan = new Scanner(System.in)) { // This line is causing the error.
System.out.print("Enter Username: ");
username = scan.next();
System.out.print("Enter Password: ");
password = scan.next();
}
if(getUsernamesList().contains(username))
if(password.equals(getPasswordsList().get(getUsernamesList().indexOf(username)))) return username;
else return "-1";
else return "-1";
}
推荐答案
c $ c> System.in (全局变量)。 请,不要这样做。每个地方你有
You're closing System.in
(a global-variable). Please, do not do that. Everywhere you have
try(Scanner scan = new Scanner(System.in))
保证 System.in
将关闭
(d)。一旦它是关闭
(d)你不能再读取(或者你得到你提到的异常
)。此外,您可以使用调试符号进行编译(或使用IDE的内置调试器或 jdb )。 扫描仪。关闭()
Javadoc说(部分),
guarantees that System.in
will be close
(d). Once it's close
(d) you can't read from it again (or you get your mentioned Exception
). Also, you can compile with debug symbols (or step into it with your IDE's built-in debugger or jdb as applicable). The Scanner.close()
Javadoc says (in part),
If this scanner has not yet been closed then if its underlying readable also implements the
Closeable
interface then the readable'sclose
method will be invoked
这篇关于Java:尝试(扫描仪扫描=新的扫描仪(System.in){}导致异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!