我正在尝试编写代码来从文本文件中读取信息,我需要找出每个单词由空格分隔的次数。然后我需要按字母顺序输出每个单词的计数。我希望使用TreeMap,keySet()和Iterator。我的代码非常不完整,我很困惑。
import java.util.HashMap;
import java.util.Map
public class WordCount<E extends Comparable<E>> {
private static Map<String, Integer> map = new HashMap<String, Integer>();
static {
fillMap(map, "Alice.txt");
}
private static void fillMap(Map<String, Integer> map, String fileName) {
}
}
答案 0 :(得分:1)
这是您要求的确切代码。它将保存每一个字并计算它们。如果它得到的单词不存在,它会将它添加到Map中,如果它,它会增加它的值。最后,它将打印所有键和值。 使用它,如果你有任何问题,请问。
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
/*
* @author Mr__Hamid
*/
public class overFlow {
public static void main(String[] args) throws FileNotFoundException, IOException {
Map m1 = new HashMap();
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
String[] words = line.split(" ");//those are your words
for (int i = 0; i < words.length; i++) {
if (m1.get(words[i]) == null) {
m1.put(words[i], 1);
} else {
int newValue = Integer.valueOf(String.valueOf(m1.get(words[i])));
newValue++;
m1.put(words[i], newValue);
}
}
sb.append(System.lineSeparator());
line = br.readLine();
}
}
Map<String, String> sorted = new TreeMap<String, String>(m1);
for (Object key : sorted.keySet()) {
System.out.println("Word: " + key + "\tCounts: " + m1.get(key));
}
}
}