简体   繁体   中英

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

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

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

Have you tried not using the try?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM