我正在尝试创建一个程序作为我自己的哈希图教程。我要求用户输入文本并尝试将其拆分为哈希图,然后如果单词重复则增加计数。这是我的程序:
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
我需要改变什么才能得到:
随机3
另外,我是否需要使用迭代器来打印哈希图,或者我使用的可以吗?
你的初始化是错误的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));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)