您的初始化错误
hm.put(splitted[i], i)。您应该初始化为0或1(以计数,而不是索引)。
因此,请首先执行此循环。
for (int i = 0; i < splitted.length; i++) { if (!hm.containsKey(splitted[i])) { hm.put(splitted[i], 1); } else { hm.put(splitted[i], (Integer) hm.get(splitted[i]) + 1); } }然后再做一个循环(遍历HashMap的键)并打印计数。
for (Object word : hm.keySet()){ System.out.println(word + " " + (Integer) hm.get(word)); }


