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

和自甴很熟 提交于 2019-11-28 14:42:20

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