简体   繁体   English

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

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

I'm trying to just create a basic word counter for a specific word inside the "list.txt" document. 我正在尝试为“ list.txt”文档中的特定单词创建一个基本单词计数器。 The code I'm using right now is not scanning "Customer" even though Customer appears a few times in the word document already, I've tried making a String variable with the value of "Customer" instead but that also didn't work, could anyone perhaps correct where I've gone wrong? 我现在使用的代码不会扫描“ 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;
}

You did not open the file. 您没有打开文件。

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

If you use new Scanner("list.txt") it just scan the text "list.txt". 如果您使用new Scanner("list.txt")则只需扫描文本“ list.txt”。

You passed a parameter of type String to the Scanner in which the Scanner would only produce values from that specified String. 您将String类型的参数传递给Scanner,其中Scanner仅会从该指定的String中产生值。

In order for the scanner to produce values from an actual file, you can pass in a File object defining the path to the file. 为了使扫描仪能够从实际文件中生成值,您可以传入定义文件路径的File对象。

To do this, you should initialize a new File object and pass it the path to the file you're trying to scan. 为此,您应该初始化一个新的File对象,并将其路径传递给您要扫描的文件。 Once you do this you can then pass the File object to the Scanner. 完成此操作后,即可将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