0

在 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(counter));

异常是什么意思?

4

3 回答 3

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

看这里

于 2013-04-24T14:40:06.217 回答
1

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

        String next = file.next();
        for(int counter = 0 ; counter < next.length(); counter ++) {
            System.out.println(next.charAt(counter));    
        }
于 2013-04-24T14:38:37.227 回答
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));    
            }
        }
    }
}
于 2013-04-24T14:39:54.447 回答