f3d*_*d0r 0 java for-loop hashmap count
我正在尝试为自己创建一个程序作为哈希图的教程。我要求用户输入文本,然后尝试将其拆分为哈希图,如果单词重复,则增加计数。这是我的程序:
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)); }
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我输入“随机随机随机”时,我得到:随机0随机1随机2
我需要更改什么才能得到:random 3另外,我是否需要使用迭代器打印出哈希图,还是我使用了OK?
您的初始化错误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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后再做一个循环(遍历HashMap的键)并打印计数。
for (Object word : hm.keySet()){
System.out.println(word + " " + (Integer) hm.get(word));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19208 次 |
| 最近记录: |