Java: try(Scanner scan = new Scanner(System.in) { } causing an exception

六月ゝ 毕业季﹏ 提交于 2019-11-27 08:43:56

问题


Using try(Scanner scan = new Scanner(System.in)) { } is causing

Exception in thread "main" java.util.NoSuchElementException

When I try to debug it says that

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

and shows the below code

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

回答1:


You're closing System.in (a global-variable). Please, do not do that. Everywhere you have

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

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's close method will be invoked




回答2:


Have you tried not using the try?

String username;
String password;
Scanner scan = new Scanner(System.in);
System.out.print("Enter Username: ");


来源:https://stackoverflow.com/questions/32042139/java-tryscanner-scan-new-scannersystem-in-causing-an-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!