I am trying to find out the frequency of characters in string using java tree map. Everything is going fine .But extra lin of string is getting added when i am getting output for one particlar case .
import java.awt.Menu;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class Main {
public static void main(String [] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the input string");
String s1=s.nextLine();
Map<Character,Integer> map=new TreeMap<Character,Integer>();
for(int i = 0; i < s1.length(); i++){
char c = s1.charAt(i);
Integer val = map.get(new Character(c));
if(val != null){
map.put(c, new Integer(val + 1));
}else{
map.put(c,1);
}
}
for(Map.Entry<Character,Integer> en:map.entrySet()){
int count=en.getValue();
System.out.printf("%c : ",en.getKey());
for(int i=0;i<count;i++)
System.out.printf("*");
System.out.printf("\n");
}
}
}
for Input: Kohli is the man of the match
this should be the output K : * a : ** c : * e : ** f : * h : **** i : ** l : * m : ** n : * o : ** s : * t : ***
but am getting this: :****** K :* a :** c :* e :** f :* h :**** i :** l :* m :** n :* o :** s :* t :***
How to fix it.
There are 6 whitespaces in the string you entered. That's why you get this output. A whitespace is a character too.
If you want to remove this whitespaces, you can update your code like this:
String s1=s.nextLine().replaceAll(" ","");