Input a string "hello word", print l:3 o:2 e:1 d:1 h:1 r:1 w:1
Page 1 of 1
Input a string "hello word", print l:3 o:2 e:1 d:1 h:1 r:1 w:1
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"));
}
}
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
Similar topics
» print all subsets of an array whose sum equals one number
» Combinations of a String/Array
» Permutations of a String
» Reverse a String
» How to find the longest palindrome in a string
» Combinations of a String/Array
» Permutations of a String
» Reverse a String
» How to find the longest palindrome in a string
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum