// WordCount.java // Count how many words are in a file of text // P. Conrad, for UCSB CS5JA, 03/05/2008 import java.util.Scanner; // for Scanner import java.io.*; // for reading from files public class WordCount { public static void main(String args[]) { Scanner fileInput = null; // Make sure there is exactly one argument if (args.length!=1) { System.out.println("Error: you should pass exactly one argument"); System.out.println("That argument should be the filename"); System.exit(1); // non zero status code signifies an error } // Store the first argument in the variable "filename" String filename = args[0]; // Try to open the file try { fileInput = new Scanner(new BufferedReader(new FileReader(filename))); } catch (IOException e) { System.out.println("Error: could not open " + filename); System.out.println("The error was " + e.toString()); System.exit(2); // error number two! } System.out.println("Successfully opened the file " + filename); System.out.println("Now, we'll count the lines..."); // If that worked, read through every line in the file // and count how many there are int lines = 0; // start counter at zero int words = 0; // start counter at zero while (fileInput.hasNextLine()) { lines++; // count this line String thisLine = fileInput.nextLine(); // read it and move past it // count the words int thisLinesWordCount = howManyWords(thisLine); System.out.println("the line |" + thisLine + "| has " + thisLinesWordCount + " words"); // add that to the count words += thisLinesWordCount; } // Output the result System.out.println("This file has " + lines + " lines of text"); System.out.println("This file has " + words + " words of text"); } // return how many words are on a given line int howManyWords(String line) { String theWords[] = line.split("\\s"); // splits on 'whitespace' return theWords.length; } }