Question:
Enter a string manually. Only lowercase letters are allowed. Count and output the number of times each character appears in the string. Prompt to use Map
Example: Enter aaabbbccc
Output: A 3
B 3
C 3
Analysis
Directly run the Code:
Import java. util. iterator;
Import java. util. Map;
Import java. util. Set;
Import java. util. treemap;
Public class testcharacount {
Public static void main (string ARGs []) {
String strin = "aaabbbccc ";
Testcharacount Tc = new testcharacount ();
Map <character, integer> mtemp = tc. characount (strin );
Set <character> Ks = mtemp. keyset (); // generate an index set
For (iterator <character> it = ks. iterator (); it. hasnext ();) {// traverse index values
Char c = it. Next ();
System. Out. println (C + "" + mtemp. Get (c ));
}
}
Public Map <character, integer> characount (string strin ){
String tempstr = strin;
// The map is sorted according to the natural ordering of its keys
// Treemap stores values in the natural order of keys
Map <character, integer> M = new treemap <character, integer> ();
Char [] STRC = tempstr. tochararray ();
For (INT I = 0; I <STRC. length; I ++ ){
Integer COUNT = M. Get (STRC [I]);
If (null = count)
Count = 0;
Count ++;
M. Put (STRC [I], count );
}
Return m;
}
}