Java - Scanner拒绝关闭?

时间:2014-03-15 16:05:12

标签: java file

我创建了一个程序,它接收一个文件并分别输出该文件中的行数,字数和字符数。

我的问题是,当我编译程序时,它被“卡住”并且在交互窗格(或控制台)上没有输出任何内容。

while循环应该终止,新的扫描程序对象应该覆盖旧的。

public static void main(String[] args) throws FileNotFoundException
{

    String[] filenames = new String[]{"cat.txt", "dog.txt", "mouse.txt", "horse.txt"} ;
    int totalLines = 0, totalWords = 0, totalCharacters = 0 ;

    for (String filename : filenames) 
    {
        int lines = 0, words = 0, characters = 0;

        try {

            Scanner scanner_lines = new Scanner (new File(filename)); //Reading Lines
            while (scanner_lines.hasNextLine()){
                lines++;
            }
            scanner_lines.close();

            Scanner scanner_words = new Scanner (new File(filename)); //Reading Words
            while (scanner_words.hasNext()){
                words++;
            }
            scanner_words.close();

            Scanner scanner_chars = new Scanner (new File(filename)); //Reading Characters
            scanner_chars.useDelimiter("");
            while (scanner_chars.hasNext()){
                characters++;
            }
            scanner_chars.close();
        } // end of try
        catch (FileNotFoundException e) {}

        System.out.println (lines + " " + words + " " + characters);

    }
}

1 个答案:

答案 0 :(得分:2)

循环需要消耗线,而不仅仅是确定它的存在:

Scanner scanner_lines = new Scanner (new File(filename)); //Reading Lines
while (scanner_lines.hasNextLine()){
    scanner_lines.nextLine();   // this is critical
    lines++;
}