使用 input/output 程序计算单词在 java 中出现的次数

Counting Occurrences of a word using a input/output program in java

如何使用 input/output 程序找到包含五个或更多字母的文件中出现次数最多的单词?这是我的入门代码

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


public class FileIOtest {

/**
 * @param args
 * @throws FileNotFoundException 
 */
public static void main(String[] args) throws FileNotFoundException {
    // TODO Auto-generated method stub
    File file = new File ("myfile.txt");
    Scanner inputFile = new Scanner(file);

    while(inputFile.hasNext())
    {
        String str =inputFile.nextLine();
        System.out.println(str);
    }
    inputFile.close();

}

}

我会制作一个hashmap,它在单词和出现次数计数器之间保存键值对。

Map<String, Integer> myMap = new HashMap<String, Integer>();

你应该用 white-space 分割每一行,然后遍历分割字符串的数组。然后,您可以检查单词是否为 5 个或更多字符,并在 hashmap

中增加计数器
    String str = inputFile.nextLine();
    String[] parts = str.split(" ");
    for(int x  = 0; x < parts.length; x++)
    {
        String word = parts[x];
       if(word.length() >= 5)
       {
           if(myMap.containsKey(word))
           {
              myMap.put(word, myMap.get(word) + 1);
           }
           else
           {
              myMap.put(word, new Integer(1));
           }
       }
    }

然后在最后你可以用myMap.entrySet()得到HashMap的内部集合。然后通过该集合进行交互以找到第一、第二、第三等最常见或最不常见的单词。