Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static String[] words = { "red", "blue", "yellow", "green" };
- public static void main(String[] args) throws FileNotFoundException, IOException {
- System.out.println("This program will count the occurences of the specific words from a text file.");
- System.out.println("nThe words to be counted are; red, blue, yellow, and green.n");
- Map map = new HashMap();
- try (BufferedReader br = new BufferedReader(new FileReader("colours.txt"))) {
- StringBuilder sb = new StringBuilder();
- String line = br.readLine();
- while (line != null) {
- 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.,
- for (int i = 0; i < words.length; i++) {
- if (map.get(words[i]) == null) {
- map.put(words[i], 1);
- }
- else {
- int newValue = Integer.valueOf(String.valueOf(map.get(words[i])));
- newValue++;
- map.put(words[i], newValue);
- }
- }
- sb.append(System.lineSeparator());
- line = br.readLine();
- }
- }
- Map<String, String> sorted = new TreeMap<String, String>(map);
- for (Object key : sorted.keySet()) {
- System.out.println(key + ": " + map.get(key));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement