-2

我有这段代码,运行程序时收到错误消息。我做错了什么吗?

import java.io.*;
import java.util.*;

public class countLines {
    public static void main(String[] args) throws Exception {
        int count = 0;
        int word = 0;
        File f = new File("file.txt");
        Scanner input = new Scanner(f);
        while(input.hasNext()){
            String words = input.next();
            word++;
        }
        while (input.hasNextLine()) {
            input.nextLine();
            count++;
        }
        input.close();
        System.out.println("Number of Line: " + count);
        System.out.println("This file has " + word + " words.");
    }
}
4

1 回答 1

3

在你的第一个while循环中,你正在阅读你的文件,然后是你close。然后,在您的下一个while循环中,您尝试再次从文件中读取。这将触发错误,因为文件已关闭!

于 2013-02-16T21:42:55.017 回答