1

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

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();

}

}
4

1 回答 1

0

我会hashmap在单词和出现次数的计数器之间创建一个键值对。

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

您应该用空格分割每一行,然后遍历分割字符串的数组。然后,您可以检查单词是否为 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));
           }
       }
    }

然后在最后你可以得到HashMap's internal set with myMap.entrySet()。然后在该集合中进行交互以找到第一个、第二个、第三个等最常见或最不常见的单词。

于 2015-03-20T02:42:43.053 回答