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

前端 未结 2 1993
醉酒成梦
醉酒成梦 2020-12-12 06:41

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

Exception in thread \"main\" java.util.NoSuchElementException

相关标签:
2条回答
  • 2020-12-12 07:28

    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

    0 讨论(0)
  • 2020-12-12 07:30

    Have you tried not using the try?

    String username;
    String password;
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter Username: ");
    
    0 讨论(0)
提交回复
热议问题