-5

User will enter a String, For instance if the user enters YYYCZZZZGG: Program will evaluate the frequency of characters in the string. For YYYCZZZZGG string, C is seen only for 1, G is repeated 2, Y has a frequency of 3, and Z’s frequency is 4.

after finding number of each letter how can I draw a bar graph using the numbers of the programs output?

relaxon
  • 13
  • 3
  • 7
    *"User will enter a String, .. Program will evaluate the frequency"* Programmer will show some effort.. – Andrew Thompson Apr 30 '13 at 09:07
  • If you are okay with order N solution just go through all the letters then create a map M like M['C']=M['C']+1 for each occurance and then iterate over the map. – specialscope Apr 30 '13 at 09:11

5 Answers5

1

Use Apache StringUtils:

It contains a method that can be used like StringUtils.countMatches("YYYCZZZZGG", "Y");

Vineet Singla
  • 1,609
  • 2
  • 20
  • 34
0
int count = StringUtils.countMatches("YYYCZZZZGG", "C");

Just a matter of copy paste from Java: How do I count the number of occurrences of a char in a String?

Community
  • 1
  • 1
Toon Casteele
  • 2,479
  • 15
  • 25
0
    String str="YYYCZZZZGG";
    Map<Character,Integer> map=new HashMap<Character,Integer>();

    for (char c : str.toCharArray()) {
        if(map.containsKey(c))
        {
            int i=map.get(c);
            i++;
            map.put(c, i);
        }
        else
        {
            map.put(c, 0);
        }
    }

    for(Map.Entry<Character, Integer> entry:map.entrySet())
    {
        char c=entry.getKey();
        int  count=entry.getValue();
    }
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user2254860
  • 76
  • 1
  • 7
0

You can do it like this:

 String s = "YYYCZZZZGG";
 Map<Character, Float> m = new TreeMap<Character, Float>();
 for (char c : s.toCharArray()) {
     if (m.containsKey(c))
            m.put(c, m.get(c) + 1);
        else
            m.put(c, 1f);
 }

 for (char c : s.toCharArray()) {
      float freq = m.get(c) / s.length();
      System.out.println(c + " " + freq);
  }

Or you can use StringUtils class like:

System.out.println("The occurrence of Z is "+StringUtils.countMatches(s, "C"));
Shreyos Adikari
  • 12,348
  • 19
  • 73
  • 82
0

Try this:

public static void main(String[] args) {
    String input = "YYYCZZZZGG";
    Map<Character, Integer> map = new HashMap<Character, Integer>(); // Map
    // to store character and its frequency.
    for (int i = 0; i < input.length(); i++) {
        Integer count = map.get(input.charAt(i)); // if not in map
        if (count == null)
            map.put(input.charAt(i), 1);
        else
            map.put(input.charAt(i), count + 1);
    }
    System.out.println(map);
}

Output:

{G=2, C=1, Y=3, Z=4}
Achintya Jha
  • 12,735
  • 2
  • 27
  • 39