Hashmap 实现来计算每个字符的出现次数 [英] Hashmap implementation to count the occurrences of each character

查看:21
本文介绍了Hashmap 实现来计算每个字符的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码是计算每个字符的出现次数,它应该打印计数.但是使用我尝试过的代码,我只得到 1 我不知道我应该做哪些更改.

The below code is to count the occurence of each character and it should print the count. But with the code I have tried I get only a 1 I don't know the changes I should make.

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

class Count_CharMap {
public static void main(String[] args) {
    try
    {
        FileInputStream file = new FileInputStream("D:\trial.txt");
        DataInputStream dis = new DataInputStream(file);
        BufferedReader br = new BufferedReader(new InputStreamReader(dis));
        String Contents="";
        String str="";

        while ((Contents = br.readLine()) != null) {
            str+=Contents;
        }

        char[]char_array =str.toCharArray();
        int count = 0;
        char ch = char_array[count];
        Map<Character,Integer> charCounter=new HashMap<Character,Integer>();
        for(int i=0;i<str.length();i++)
        {
            if(charCounter.containsKey(char_array[i]))
            {
                charCounter.put(ch, charCounter.get(ch)+1);
            } 
            else
            {
                charCounter.put(ch, 1);
            }
       }

       for(Character key:charCounter.keySet())
       {
           System.out.println(key+""+charCounter.get(key));
       }
    } 
    catch(IOException e1){
        System.out.println(e1);
    }
    }
}

实际输出应该是这样的如果我的 trial.txt 中有 abcdabc,它应该打印一个 2 b 2c 2 d 1.

Actual output should be like If i have abcdabc in my trial.txt it should print a 2 b 2c 2 d 1.

推荐答案

在每次执行循环时,您都将 char ch 设置为相同的字符.

You're leaving char ch set as the same character through each execution of the loop.

应该是:

ch = char_array[i]; 
if(charCounter.containsKey(ch)){
     charCounter.put(ch, charCounter.get(ch)+1);
}
else
{
    charCounter.put(ch, 1);
}

在 for 循环内.

这篇关于Hashmap 实现来计算每个字符的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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