Scanner error that I can't figure out: NoSuchElementException

心不动则不痛 提交于 2019-12-07 17:42:29

When I choose option 8, in saveSurvey(), it has to create a new Scanner (in that method) because all of this is inside my main method. Could that be the issue?

Yes, that could be the issue. If that Scanner has the same source (System.in?) as kb and is close()d, that closes the underlying stream, and kb cannot get input anymore.

I figured it out.

The whole issue was caused by me not creating a static scanner in main - and when I needed it in other methods outside of main, I created new ones.

Instead of

public class MainDriver
{
    public static Scanner kb = new Scanner(System.in);
    public void main(String[] args) throws IOException 
   {

I had:

public class MainDriver
{
    public static void main(String[] args) throws IOException 
    {
        public static Scanner kb = new Scanner(System.in);

And then created new scanners in the other methods. At the end of those methods, I closed the Scanner. I guess it was closing the local scanner, because when I got rid of all close() statements that were inside the other methods, the issue disappeared.

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