单词计数器程序未生成正确数量的单词

Word counter program not producing correct number of words

我不熟悉从文件中读取文本。 我有一项任务需要打印文件中的字数。

我在 mac OS 上使用 TextEdit,它以 .rtf

结尾

当我运行以下程序时,即使文档为空,我也得到输出 5。当我添加单词时,计数不会正确增加。

谢谢。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Analyze{ 


public static void main(String[] args) throws FileNotFoundException{
    Scanner console = new Scanner(System.in);
    int words = 0; 
    System.out.println("This is a word counter");
    System.out.println("File name");
    String filename = console.next();
    File name = new File(filename);

    Scanner int2 = new Scanner(name);

    while (int2.hasNext()) {
        String temp = int2.next();
        words++;
    }

    System.out.println(words);
    }
}

问题是您正在读取 RTF 文件。

A​​ 'blank'(因为没有输入文本)使用 TextEdit 生成的 RTF 文件如下所示:

{\rtf1\ansi\ansicpg1252\cocoartf1404\cocoasubrtf130
{\fonttbl}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww10800\viewh8400\viewkind0
}

可以看到,5行对应5的输出。

要么在你的程序中解析 RTF,我怀疑你想要这样做,要么将 TextEdit 切换到纯文本模式。参见 here

您要计数的文件是 RTF 文件?它支持斜体、粗体、字体选择等等吗?在那种情况下,它可能包含一些数据,即使没有文本。您的程序不关心文件格式,因此它天真地以文本形式读取所有内容。

在您的文件上尝试 运行 odhexdump(不确定这些是否存在于 Mac OS X 上?)——他们打印文件的确切字节。真正的空文件不应产生任何输出。

如果您的计算机没有 odhexdump 程序,您可以尝试 cat。它不会将内容打印为数字,因此无法 100% 准确地查看特殊字符,但它应该能够向您演示您的文件是否为空。

除了RTF问题,还要注意

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

中的空格

A whitespace character: [ \t\n\x0B\f\r]

因此计数包括制表符、换行符等,而不仅仅是空格