Count occurence of a character in a String
<p>I have the below program that counts the occurrence of a character in a string. For example, given a string - <code>my name is stack overflow</code>, I want the output to be</p>

<pre><code>f 1 e 2 c 1 a 2 n 1 o 2 l 1 m 2 k 1 i 1 w 1 v 1 t 1 s 2 r 1 y 1
</code></pre>

<p>However, something seems to be wrong, and I am unable to figure out what. Also, please note - I do see a few programs posted in the past. <a href="http://stackoverflow.com/questions/4363665/hashmap-implementation-to-count-the-occurences-of-each-character">Possible duplicate</a>. But I would like help with my specific problem rather than using someone else' solution.</p>

<p>Here's the code:</p>

<pre><code>//Count the occurence of a character in a string
package strings;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CharacterOccurenceInAString {
    private static Map&lt;Integer, Character&gt; str = new HashMap&lt;Integer, Character&gt;();
    private static List&lt;Character&gt; charList = new ArrayList&lt;Character&gt;();
    private static Character value;

    public static void main(String[] args) {
        BufferedReader br = null;
        String input = "";
        try {
            br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Please enter a string");
            input = br.readLine();
            charOccurence(input);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    public static void charOccurence(String s) {        
        for (int i = 0; i &lt; s.length(); i++) {
            // Don't include white spaces -         
            if (Character.isWhitespace(s.charAt(i))) {
                continue;
            } else {
                str.put(i, s.charAt(i));
                charList.add(s.charAt(i));
            }
        }
        for(Character val:str.values()){
                getCount(val);
        }
    }

    static boolean flag = false;
    public static int getCount(Character c) {
        int ct = 0;
        for (int i = 0; i &lt; charList.size(); i++) {         
            c = charList.get(i);
            if (charList.contains(c)) {
                ct++;
                flag=false;
            }           
        }
        if(flag==false)
        {
        System.out.println(c + ":" + ct);
        }
        return ct;
    }
}
</code></pre>

<p>This is the output I get:</p>

<pre><code>Please enter a string
my name is stack overflow
w:21
w:21 
w:21 
w:21 
w:21 
w:21 
w:21 
w:21 
w:21 
w:21 
w:21 
w:21 
w:21 
w:21 
w:21 
w:21 
w:21 
w:21 
w:21 
w:21 
w:21
</code></pre>
