I have the below program that counts the occurrence of a character in a string. For example, given a string - my name is stack overflow
, I want the output to be
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
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. Possible duplicate. But I would like help with my specific problem rather than using someone else' solution.
Here's the 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<Integer, Character> str = new HashMap<Integer, Character>();
private static List<Character> charList = new ArrayList<Character>();
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 < 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 < charList.size(); i++) {
c = charList.get(i);
if (charList.contains(c)) {
ct++;
flag=false;
}
}
if(flag==false)
{
System.out.println(c + ":" + ct);
}
return ct;
}
}
This is the output I get:
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