Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

Java: Count occurrences of characters in text file

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...