Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- //this will seperate each word from the space. then it will add it to wordcount
- //then it will check if the word is all rdy an boject and will then add to it
- public class WordCounts extends ConsoleProgram
- {
- public void run()
- {
- String word = "";
- String input = readLine("Enter a string: ");
- HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
- input = input.toLowerCase();
- if(input.charAt(input.length() - 1) != ' ')
- {
- input += " ";
- }
- for(int i = 0; i < input.length(); i++)
- {
- if(input.charAt(i) != ' ')
- {
- word += input.charAt(i);
- }
- else
- {
- if(wordCount.containsKey(word))
- {
- int num = wordCount.get(word);
- wordCount.put(word, num + 1);
- word = "";
- }
- else
- {
- wordCount.put(word, 1);
- word = "";
- }
- }
- }
- printSortedHashMap(wordCount);
- }
- /*
- * This method takes a HashMap of word counts and prints out
- * each word and it's associated count in alphabetical order.
- *
- * @param wordCount The HashMap mapping words to each word's frequency count
- */
- private void printSortedHashMap(HashMap<String, Integer> wordCount){
- // Sort all the keys (words) in the HashMap
- Object[] keys = wordCount.keySet().toArray();
- Arrays.sort(keys);
- // Print out each word and it's associated count
- for (Object word : keys) {
- int val = wordCount.get(word);
- System.out.println(word + ": " + val);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement