我正在尝试编写一个程序,从文件中获取单词并将它们放入哈希表中。然后我必须像这样计算单词的频率和输出:单词,出现次数。 我知道我的添加方法搞砸了,但我不知道该怎么做。我是 Java 新手。
public class Hash {
private Hashtable<String, Integer> table = new Hashtable<String, Integer>();
public void readFile() {
File file = new File("file.txt");
try {
Scanner sc = new Scanner(file);
String words;
while (sc.hasNext()) {
words = sc.next();
words = words.toLowerCase();
if (words.length() >= 2) {
table.put(words, 1);
add(words);
}
}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void add(String words) {
Set<String> keys = table.keySet();
for (String count : keys) {
if (table.containsKey(count)) {
table.put(count, table.get(count) + 1);
} else {
table.put(count, 1);
}
}
}
public void show() {
for (Entry<String, Integer> entry : table.entrySet()) {
System.out.println(entry.getKey() + "\t" + entry.getValue());
}
}
public static void main(String args[]) {
Hash abc = new Hash();
abc.readFile();
abc.show();
}
}
这是我的文件.txt
one one
two
three
two
输出:
two , 2
one , 5
three , 3
最佳答案
Set<String> keys = table.keySet();
for (String count : keys) {
if (table.containsKey(count)) {
table.put(count, table.get(count) + 1);
} else {
table.put(count, 1);
}
}
现在,您正在递增 map 中已有的键。相反,我不认为你想遍历任何东西,你只想为 words
增加 if
条件,我认为它实际上只代表一个词。
if (table.containsKey(words)) {
table.put(words, table.get(words) + 1);
} else {
table.put(words, 1);
}
关于java - 将词频添加到哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30084511/