Advertisement
allerost

countwords

Jan 19th, 2020
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.29 KB | None | 0 0
  1. package ar223ni_assign4;
  2.  
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileReader;
  6. import java.util.Scanner;
  7.  
  8. public class CountingWords {
  9.     public static void main(String[] args) throws FileNotFoundException {
  10.         //Add all my scanners and the filepaths
  11.         Scanner sc = new Scanner(System.in);
  12.         File testFile = new File("C:\\Users\\Greattech\\Downloads\\lovecraft.txt");
  13.         FileReader fileReader = new FileReader("C:\\Users\\Greattech\\Downloads\\lovecraft.txt");
  14.         Scanner readFile = new Scanner(fileReader);
  15.         String currentRow = "";
  16.         int totalWords = 0;
  17.         String words[] = null;
  18.         boolean skipLine = false;
  19.        
  20.  
  21.         while (readFile.hasNextLine()) {
  22.             currentRow = readFile.nextLine();
  23.             //Use regex to remove empty lines
  24.             currentRow = currentRow.replaceAll("(?m)^[ \t]*\r?\n", "");
  25.             //Use regex to tell what seperats words and throw them onto a empty array.
  26.             words = currentRow.split("[ ]");
  27.             //Take the total amout of words and add the size of the array to it! for the total amout of words
  28.             totalWords = totalWords + words.length;
  29.         }
  30.         System.out.println("Number of words: " + totalWords);
  31.  
  32.    
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement