gpt4 book ai didi

Java: try(Scanner scan = new Scanner(System.in) { } 导致异常

转载 作者:行者123 更新时间:2023-12-01 07:54:29 24 4
gpt4 key购买 nike

使用 try(Scanner scan = new Scanner(System.in)) { } 导致

Exception in thread "main" java.util.NoSuchElementException

当我尝试调试时,它说

Variable information not available, source compiled without -g option.

并显示以下代码

    public Scanner(InputStream source) {
this(new InputStreamReader(source), WHITESPACE_PATTERN);
}

我使用这一行的方法之一:

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

最佳答案

您正在关闭System.in(全局变量)。 不要这样做。随处可见

try(Scanner scan = new Scanner(System.in))

保证System.in关闭(d)。一旦关闭(d),您将无法再次读取它(或者您会收到提到的异常)。此外,您还可以使用调试符号进行编译(或使用 IDE 的内置调试器或 jdb (如果适用)进行单步调试)。 Scanner.close() Javadoc 说(部分),

If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked

关于Java: try(Scanner scan = new Scanner(System.in) { } 导致异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32042139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com