java - Count occurence of a character in a String -


this question has answer here:

i have below program counts occurrence of character in string. example, given string - my name stack overflow, want output be

f 1 e 2 c 1 2 n 1 o 2 l 1 m 2 k 1 1 w 1 v 1 t 1 s 2 r 1 y 1 

however, seems wrong, , unable figure out what. also, please note - see few programs posted in past. possible duplicate. specific problem rather using else' solution.

here's code:

//count occurence of character in 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 string");             input = br.readline();             charoccurence(input);         } catch (exception ex) {             ex.printstacktrace();         }     }     public static void charoccurence(string s) {                 (int = 0; < 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;         (int = 0; < 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 output get:

please enter string name 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 

if want character count, better if map< character, integer> rather map< integer,character>.

map<character, integer> charcount = new hashmap<character,integer>(); (int = 0; < s.length(); i++) {     integer count = charcount.get(s.charat(i));     if (count == null)         count = 0;     charcount.put(s.charat(i), ++count); } 

this map of characters how many times occur.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -