java - 计算文本文件中的特定单词 - Java

标签 java file-read

我有一个文本文件,我想计算我定义的特定单词的总数。

我的代码:

    String word1 = "aa";
    String word2 = "bb";

    int wordCount = 0;

     //creating File instance to reference text file in Java
    File text = new File("D:/project/log.txt");

    //Creating Scanner instnace to read File in Java
    Scanner s = new Scanner(text);

    //Reading each line of file using Scanner class
    while (s.hasNext()) {
        totalCount++;
        if (s.next().equals(word1) || s.next().equals(word2)) wordCount++;
    }

    System.out.println("Word count:  " + wordCount);

但是,它只计算“aa”的数量。它不计算“bb”的数量。 可能是什么问题?

最佳答案

正如其他人所说:问题的根源是您调用 next() 两次。只是提示如何使您的算法易于扩展:

Set<String> words = new HashSet<>(Arrays.asList("aa", "bb"));
...
while (s.hasNext()) {
    totalCount++;
    if (words.contains(s.next())) wordCount++;
}

关于java - 计算文本文件中的特定单词 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27106152/

相关文章:

Java util 首选项构造函数

java - JPanel 与 JTextField 或 JLabel 不更新

c++ - 如何从文件中读取值。分词器

Python;我们如何复制txt文件中的随机行并删除同一行?

c++ - 从 C++ 中的 CSV 文件中读取特定元素

java - Hibernate保存和SQL插入有什么区别?

java - 如何根据当前秒数获取第二天的第一秒?

java - 区分libgdx中的 "Drag"和 "Touch Down then immidiately Touch Up"

sql-server - Delphi:如何有效地读取大的二进制文件,将其转换为十六进制以将其作为 varbinary(max) 参数传递?

ruby - 在Ruby中读取文件时如何删除换行符