调用.next()方法时出现扫描仪NoSuchElementException [英] Scanner NoSuchElementException when calling .next() method

查看:100
本文介绍了调用.next()方法时出现扫描仪NoSuchElementException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,出现此异常:

In Java, I'm getting this Exception:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at com.reading.text.Activity3.readFile(Activity3.java:22)
    at com.reading.text.Activity3.main(Activity3.java:10)

通过此Java代码:

public static void main(String args[])
{
    readFile("C:/Users/forsakendoll/Desktop/boom.txt");
}

public static void readFile(String path) {
    Scanner file = null;
    try {
        file = new Scanner(new File (path));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        while (file.hasNext()) {
            for(int counter = 0 ; counter < file.next().length(); counter ++) {
                System.out.println(file.next().charAt(counter));    
            }
        }
    }
}

引发

System.out.println(file.next().charAt(counter));

System.out.println(file.next().charAt(counter));

该异常是什么意思?

推荐答案

在循环的每次迭代中,您都两次调用.next(),因此,当您接近结尾时,您将跳出列表的结尾并进入编译器告诉你那里什么都没有.

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.

代替此:

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));    
}  

在此处查看

这篇关于调用.next()方法时出现扫描仪NoSuchElementException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆