Input a string "hello word", print l:3 o:2 e:1 d:1 h:1 r:1 w:1

Go down

Input a string "hello word", print l:3 o:2 e:1 d:1 h:1 r:1 w:1

Post  skyboard on Sun Sep 18, 2011 5:01 pm

When I run the following code, it only returns

d:1e:1h:1l:1o:1r:1w:1


Have no idea where went wrong


import java.util.Collection;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;


public class Findfrequency {
public String find(String s){
char[] ch=s.toCharArray();
Hashtable<Character,Integer> hash=new Hashtable<Character,Integer>();
for(int i=0;i<ch.length;i++){
Character temp=new Character(ch[i]);
if(!hash.contains(temp)){
hash.put(temp, new Integer(1));
}
else{
Integer in=hash.get(temp);
in++;
hash.put(temp, new Integer(in));
}
}
Vector v=new Vector(hash.keySet());
Collections.sort(v);
Iterator it=v.iterator();
String str="";
while(it.hasNext()){
Character element=(Character)it.next();
int a=hash.get(element).intValue();
str+=element+":"+a;

}
return str;

}

public static void main(String[] args){
Findfrequency f=new Findfrequency();
System.out.println( f.find("helloworld"));
}
}

skyboard

Posts : 31
Join date : 2011-09-03

View user profile

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum