Scanner NoSuchElementException when calling .next() method

陌路散爱 提交于 2019-12-01 14:19:02
samba

You are calling .next() twice on every iteration of the loop, so when you are near the end, you jump off the end of the list and the compilter tells you there is nothing there.

Instead of this:

for(int counter = 0 ; counter < file.next().length(); counter ++) {
    System.out.println(`file.next()`.charAt(counter));    
}

Do this instead:

String temp = file.next();
for(int counter = 0 ; counter < next.length(); counter ++) {
    System.out.println(temp .charAt(counter));    
}  

SEE HERE

Don't call next() so much times! It actually go to the next element when you call it. If you need to use it more than once, put it inside a variable and use it.

        String next = file.next();
        for(int counter = 0 ; counter < next.length(); counter ++) {
            System.out.println(next.charAt(counter));    
        }

The Scanner.next() method will move the internal iterator along one. Your code should be:

public static void readFile(String path) {
    Scanner file = null;
    try {
        file = new Scanner(new File (path));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        while (file.hasNext()) {
            String next = file.next();
            for(int counter = 0 ; counter < next.length(); counter ++) {
                System.out.println(next.charAt(counter));    
            }
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!