您如何使用输入/输出程序在具有五个或更多字母的文件中找到最多出现的单词?这是我的入门代码
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));
}
}
}
然后,最后可以使用来获取HashMap
的内部设置myMap.entrySet()
。然后遍历该集合以找到最常见或最不常见的第一个,第二个,第三个单词。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句