Scanner objects in methods and NoSuchElementException [duplicate]

╄→尐↘猪︶ㄣ 提交于 2019-11-29 17:17:07

When you call scanner.close() it not only closes scanner, but also stream from which it reads data, in this case System.in. So if you are going use System.in later don't close it (if it is closed, we can't reopen it and read any data from it, hence exception).

Your second code example solves this problem because Scanner is being closed when you are sure that nothing else will be read from input stream.

BTW it seems that you mixed places where nextLine and nextInt should be invoked (nextLine seems to be more appropriate for inputAndPrintString while nextInt for inputAndPrintNumber).

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