如何使用输入/输出程序找到包含五个或更多字母的文件中出现次数最多的单词?这是我的入门代码
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>();
您应该用空格分割每一行,然后迭代分割字符串的数组。然后,您可以检查该单词是否包含 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
的内部集合。然后通过该集合进行交互,找到第一个、第二个、第三个等最常见或最不常见的单词。
关于java - 使用java中的输入/输出程序计算单词的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29158218/