Java:计算文本文件中字符的出现 [英] Java: Count occurrences of characters in text file

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

问题描述

这是程序的一部分,该程序将计算文本文件中每个字母的出现次数。我希望它打印类似A:4 B:23 C:32的内容,而不是打印A:0B:0C:0A:0B:0C:0A:0B:0C:0,它甚至无法找到每个出现的所有位置信件。我在这里做错了什么?

This is part of a program that will count the occurrences of each letter within the text file. I want it to print something like A:4 B:23 C:32 and instead it prints A:0B:0C:0A:0B:0C:0A:0B:0C:0 which does not even find all of the occurrences of each letter. What am I doing wrong here? Thanks for the help!!

             char ch = line.charAt(0);

                int Acounter=0;
                int Bcounter=0;
                int Ccounter=0;
                switch (ch)
                {
                    case 'A':
                       Acounter++;
                        break;
                    case 'B':
                        Bcounter++;
                        break;
                    case 'C':
                        Ccounter++;
                        break;
                }

             bw.write ("A:" + Acounter);
             bw.write ("B:" + Bcounter);
             bw.write ("C:" + Ccounter);


推荐答案

char ch [] = s.toCharArray();
Map map = new HashMap();

char ch[] = s.toCharArray(); Map map = new HashMap();

    for (int i = 0; i < ch.length; i++) {
        int count = 0;
        for (int j = 0; j < ch.length; j++) {
            if (ch[i] == ch[j])
                count++;
        }
        map.put(ch[i], count);

    }
    Iterator it = map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry) it.next();
        System.out.println("count of " + pairs.getKey() + " = "
                + pairs.getValue());
    }

这篇关于Java:计算文本文件中字符的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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