tdulik

Histogram of words in text files

Apr 2nd, 2020
212
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package words_occurences;
  2.  
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.util.LinkedList;
  6. import java.util.Scanner;
  7.  
  8. /*class wordInfo {
  9.     String word;
  10.     int occurences;
  11.  
  12.     public wordInfo(String word, int occurences) {
  13.         this.word = word;
  14.         this.occurences = occurences;
  15.     }
  16. }
  17. */
  18. public class MainLinkedList {
  19.  
  20.     public static void main(String[] args) {
  21.         // TODO Auto-generated method stub
  22.         File f = new File("text.txt");
  23.  
  24.         LinkedList<wordInfo> words = new LinkedList<wordInfo>();
  25.         try {
  26.             Scanner sc = new Scanner(f);
  27.             // sc.useDelimiter("\\s\\p{Punct}");
  28.             while (sc.hasNext()) {
  29.                 String str = sc.next();
  30.                 boolean found = false;
  31.                 for (wordInfo i : words) {
  32.                     if (i.word.equals(str)) {
  33.                         i.occurences++;
  34.                         found = true;
  35.                         System.out.println("Found! word=" + str + ", occurences=" + i.occurences);
  36.                     }
  37.                 }
  38.                 if (!found)
  39.                     words.add(new wordInfo(str, 1));
  40.             }
  41.             System.out.println("Word:   Occurences:");
  42.             for (wordInfo i : words) {
  43.                 System.out.println(i.word + "   " + i.occurences);
  44.             }
  45.  
  46.             sc.close();
  47.         } catch (FileNotFoundException e) {
  48.             // TODO Auto-generated catch block
  49.             e.printStackTrace();
  50.         }
  51.  
  52.     }
  53.  
  54. }
RAW Paste Data