Issue
Hey i am using Blue J and I have to use the StringTokenizer method to find the frequency of the words. I am easily able to do that but am not able to think of a method to not print repeated words.
import java.util.*;
class freq_wrd
{
public static void main()
{ Scanner ob=new Scanner(System.in);
System.out.println("Enter String to read");
String str = ob.nextLine();
int i,j;
StringTokenizer st = new StringTokenizer(str,"!@#$=-%^&*()_+ |}{][|<>?>,./:';");
int n = st.countTokens();
String a[]=new String[n];
for(i=0;i<n;i++)
{
a[i]=st.nextToken();
}
for(i=0;i<n;i++)
{ int freq=0;
for(j=0;j<n;j++)
{
if(a[i].equals(a[j]))
freq+=1;
}
System.out.println(a[i] + " = "+freq);
}
}
}
Solution
The string tokenizer class allows you to break a string into tokens, but it cannot help you to calculate frequencies of every word. To do this for example you can use a Map structure to store String word and Integer frequency. In the following example I'm using a TreeMap because in this way I can print words and frequencies using lexicographic order for words.
Map<String, Integer> freq = new TreeMap<>();
for (String word : words) {
int count = freq.containsKey(word) ? freq.get(word) : 0;
freq.put(word, count + 1);
}
for (String word: freq.keySet()) {
System.out.println(word + " = "+ freq.get(word));
}
Answered By - dariosicily
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.