使用hashmap创建文本的字数 [英] Create word count of text using hashmap

查看:162
本文介绍了使用hashmap创建文本的字数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个程序作为hashmap的自己的教程。我请求用户输入文本,并尝试将其拆分成哈希表,然后如果单词重复,增加计数。这是我的程序:

I am trying to create a program as a tutorial for myself for hashmaps. I ask the user into text and try to split it into hashmaps and then increase the count if the word repeats. This is my program:

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

When I input "random random random", I get: random 0 random 1 random 2

更改所以我得到:
random 3
此外,我需要使用迭代器打印出hashmap,或者是我使用的确定?

What do I need to change so I get: random 3 Also, do I need to use an iterator to print out the hashmap, or is what I used OK?

推荐答案

您的初始化是错误的 hm.put(splitted [i],i)
您应该初始化为0或1(计数,而不是索引)。

Your initialization is wrong hm.put(splitted[i], i). You should initialize to 0 or to 1 (to count, not to index).

因此首先执行此循环。

        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);
            }
        }

然后再做一个循环

        for (Object word : hm.keySet()){
            System.out.println(word + " " + (Integer) hm.get(word));
        }

这篇关于使用hashmap创建文本的字数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆