Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

count occurrence of word in string...HELP!!!!!

843785Feb 25 2009 — edited Feb 25 2009
this is require to count Occurrences of word in string..
but got error..i don't know how to solve it..






import java.util.*;
import javax.swing.JOptionPane;

public class CountOccurrenceOfWords {
public static void main(String[] args) {
//Prompt the user to enter a string
String s = JOptionPane.showInputDialog("Enter a string:");


// Create a hash map to hold words as key and count as value
Map<String, Integer> hashMap = new HashMap<String, Integer>();

String[] words = text.split("[ ]");
for (int i = 0; i < words.length; i++) {
if (words.length() > 1) {
if (hashMap.get(words[i]) != null) {
int value = hashMap.get(words[i]).intValue();
value++;
hashMap.put(words[i], value);
}
else
hashMap.put(words[i], 1);
}
}

//Count each Word in the string
// Create a tree map from the hash map
Map<String, Integer> treeMap =
new TreeMap<String, Integer>(hashMap);

// Display mappings
System.out.println("Display words and their count in " +
"ascending order of the words");
System.out.print(treeMap);
}


}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 25 2009
Added on Feb 25 2009
6 comments
549 views