Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...