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

前端 未结 2 2016
醉酒成梦
醉酒成梦 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

提交回复
热议问题