Java: Count occurrences of characters in text file

你离开我真会死。 提交于 2019-12-13 22:17:43

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/27242095/java-count-occurrences-of-characters-in-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!