Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

debugging - 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";
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...