使用hashmap创建文本的字数

我正在尝试创建一个程序作为我自己的哈希地图教程。 我要求用户输入文本并尝试将其拆分为散列图,然后在重复该单词时增加计数。 这是我的计划:

import java.util.*; import java.lang.*; import javax.swing.JOptionPane; import java.io.*; public class TestingTables { public static void main(String args[]) { { String s = JOptionPane.showInputDialog("Enter any text."); String[] splitted = s.split(" "); HashMap hm = new HashMap(); int x; for (int i=0; i<splitted.length ; i++) { hm.put(splitted[i], i); System.out.println(splitted[i] + " " + i); if (hm.containsKey(splitted[i])) { x = ((Integer)hm.get(splitted[i])).intValue(); hm.put(splitted[i], new Integer(x+1)); } } } } } 

当我输入“随机随机随机”时,我得到:随机0随机1随机2

我需要改变什么,所以我得到:random 3另外,我是否需要使用迭代器打印出hashmap,或者我使用的是什么?

你的初始化是错误的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)); } 
 import java.util.*; import java.lang.*; import javax.swing.JOptionPane; import java.io.*; public class TestingTables { public static void main(String args[]) { { String s = JOptionPane.showInputDialog("Enter any text."); String[] splitted = s.split(" "); Map hm = new HashMap(); int x; for (int i=0; i 

您的Map声明是错误的,请记住实现Map的正确方法。

这应该工作,它是一个非常简单的实现..

  Map hm = new HashMap(); int x; for (int i = 0; i < splitted.length; i++) { if (hm.containsKey(splitted[i])) { x = hm.get(splitted[i]); hm.put(splitted[i], x + 1); } else { hm.put(splitted[i], 1); } } for (String key : hm.keySet()) { System.out.println(key + " " + hm.get(key)); }