Advertisement
Guest User

Untitled

a guest
Nov 20th, 2017
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. import java.util.*;
  2. //this will seperate each word from the space. then it will add it to wordcount
  3. //then it will check if the word is all rdy an boject and will then add to it
  4. public class WordCounts extends ConsoleProgram
  5. {
  6. public void run()
  7. {
  8. String word = "";
  9. String input = readLine("Enter a string: ");
  10. HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
  11. input = input.toLowerCase();
  12. if(input.charAt(input.length() - 1) != ' ')
  13. {
  14. input += " ";
  15. }
  16.  
  17. for(int i = 0; i < input.length(); i++)
  18. {
  19. if(input.charAt(i) != ' ')
  20. {
  21. word += input.charAt(i);
  22. }
  23. else
  24. {
  25. if(wordCount.containsKey(word))
  26. {
  27. int num = wordCount.get(word);
  28. wordCount.put(word, num + 1);
  29. word = "";
  30. }
  31. else
  32. {
  33. wordCount.put(word, 1);
  34. word = "";
  35. }
  36.  
  37. }
  38. }
  39. printSortedHashMap(wordCount);
  40. }
  41.  
  42. /*
  43. * This method takes a HashMap of word counts and prints out
  44. * each word and it's associated count in alphabetical order.
  45. *
  46. * @param wordCount The HashMap mapping words to each word's frequency count
  47. */
  48. private void printSortedHashMap(HashMap<String, Integer> wordCount){
  49. // Sort all the keys (words) in the HashMap
  50. Object[] keys = wordCount.keySet().toArray();
  51. Arrays.sort(keys);
  52.  
  53. // Print out each word and it's associated count
  54. for (Object word : keys) {
  55. int val = wordCount.get(word);
  56. System.out.println(word + ": " + val);
  57. }
  58. }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement