调用.next()方法时扫描程序NoSuchElementException

时间:2013-04-24 14:36:15

标签: java file nosuchelementexception

在Java中,我得到了这个例外:

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(计数器)。);

异常是什么意思?

3 个答案:

答案 0 :(得分:3)

你在循环的每次迭代中都要调用.next()两次,所以当你接近结束时,你跳出列表的末尾,编译器告诉你那里什么都没有。

而不是:

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

请改为:

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

SEE HERE

答案 1 :(得分:1)

不要多次调用next()!当你调用它时,它实际上会转到下一个元素。如果您需要多次使用它,请将其放在变量中并使用它。

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

答案 2 :(得分:0)

Scanner.next()方法将沿一个方向移动内部迭代器。你的代码应该是:

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