Advertisement
Guest User

Untitled

a guest
Mar 24th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. static String[] words = { "red", "blue", "yellow", "green" };
  2.  
  3. public static void main(String[] args) throws FileNotFoundException, IOException {
  4.  
  5. System.out.println("This program will count the occurences of the specific words from a text file.");
  6.  
  7. System.out.println("nThe words to be counted are; red, blue, yellow, and green.n");
  8.  
  9. Map map = new HashMap();
  10.  
  11. try (BufferedReader br = new BufferedReader(new FileReader("colours.txt"))) {
  12.  
  13. StringBuilder sb = new StringBuilder();
  14.  
  15. String line = br.readLine();
  16.  
  17. while (line != null) {
  18.  
  19. words = line.split(" "); // keeping this counts all words separated by whitespace, removing it counts words in my array instead of the file, so I'll get red: 1, blue: 1, yellow: 1 etc.,
  20.  
  21. for (int i = 0; i < words.length; i++) {
  22.  
  23. if (map.get(words[i]) == null) {
  24.  
  25. map.put(words[i], 1);
  26. }
  27.  
  28. else {
  29.  
  30. int newValue = Integer.valueOf(String.valueOf(map.get(words[i])));
  31.  
  32. newValue++;
  33.  
  34. map.put(words[i], newValue);
  35. }
  36.  
  37. }
  38.  
  39. sb.append(System.lineSeparator());
  40.  
  41. line = br.readLine();
  42. }
  43. }
  44.  
  45. Map<String, String> sorted = new TreeMap<String, String>(map);
  46.  
  47. for (Object key : sorted.keySet()) {
  48.  
  49. System.out.println(key + ": " + map.get(key));
  50. }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement