繁体   English   中英

如何计算Java中txt文件中某个特定单词的出现?

[英]How do I count an occurence of a specific word in a txt file in Java?

我正在尝试为“ list.txt”文档中的特定单词创建一个基本单词计数器。 我现在使用的代码不会扫描“ Customer”,即使“ Customer”已经在Word文档中出现了几次,我也尝试用“ Customer”的值制作一个String变量,但这也没有用,也许有人可以纠正我出了问题的地方吗?

static int totalContracts() throws FileNotFoundException 
{
    Scanner scannerInput = new Scanner("list.txt");
    int count = 0;
    while (scannerInput.hasNext()) 
    { 
        String nextWord = scannerInput.next();
        System.out.println(nextWord);
        if (nextWord.equals("Customer")) 
        {
            count++;
        }
    }
    return count;
}

您没有打开文件。

Scanner scannerInput = new Scanner(new File("list.txt"));

如果您使用new Scanner("list.txt")则只需扫描文本“ list.txt”。

您将String类型的参数传递给Scanner,其中Scanner仅会从该指定的String中产生值。

为了使扫描仪能够从实际文件中生成值,您可以传入定义文件路径的File对象。

为此,您应该初始化一个新的File对象,并将其路径传递给您要扫描的文件。 完成此操作后,即可将File对象传递给Scanner。

File file_to_scan = new File("list.txt");
Scanner scanner_input = new Scanner(file_to_scan);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM