Advertisement
tdulik

Histogram of words in Java

Oct 21st, 2020
2,095
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1. package histogram_words;
  2.  
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.util.ArrayList;
  6. import java.util.Scanner;
  7.  
  8. class wordInfo {
  9.     String word;
  10.     int occurences;
  11.  
  12.     public wordInfo(String w, int o) {
  13.         word = w;
  14.         occurences = o;
  15.     }
  16.  
  17.     @Override
  18.     public boolean equals(Object obj) {
  19.         wordInfo o = (wordInfo) obj;
  20.         return word.equals(o.word);
  21.     }
  22.  
  23.     public String toString() {
  24.         return word + ": " + occurences;
  25.     }
  26. }
  27.  
  28. public class Main {
  29.  
  30.     public static void main(String[] args) {
  31.         ArrayList<wordInfo> words = new ArrayList<>();
  32.         Scanner s;
  33.         try {
  34.             s = new Scanner(new File("short.txt"));
  35.             System.out.println("Reading the wordlist...");
  36.             int count = 0;
  37.             while (s.hasNext()) {
  38.                 String nextWord = s.next();
  39.  
  40.                 wordInfo nw = new wordInfo(nextWord, 1);
  41.                 int index = words.indexOf(nw);
  42.                 if (index == -1) {
  43.                     words.add(nw);
  44.                 } else {
  45.                     wordInfo w = words.get(index);
  46.                     w.occurences++;
  47.                 }
  48.                 count++;
  49.             }
  50.             System.out.println("Finished reading: " + words);
  51.         } catch (FileNotFoundException e) {
  52.             e.printStackTrace();
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement