Hashmap实现来计算每个字符的出现次数

编程入门 行业动态 更新时间:2024-10-17 23:27:53
本文介绍了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. Please help me.

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.

推荐答案

通过每次执行循环将字符集设置为相同的字符。

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

更多推荐

Hashmap实现来计算每个字符的出现次数

本文发布于:2023-11-30 17:33:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650910.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符   次数   Hashmap

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!