import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.Scanner; public class WordAverage { public static void main(String[] args) { PrintStream out = System.out; // first command line argument is a filename String fileName = "essay.txt"; File inputFile = new File(fileName); // creating the Scanner for a file might // fail with an exception Scanner in = null; try { in = new Scanner(inputFile); } catch (IOException ex) { out.println("Error opening file named " + fileName); System.exit(1); } int numSentences = 0; int numWords = 0; StringBuilder all = new StringBuilder(); while (in.hasNextLine()) { String line = in.nextLine().trim(); all.append(line); if (!line.endsWith("-")) { all.append(" "); } } String[] words = all.toString().split("\\s"); for (String s : words) { if (s.matches(".*[.;:?!]")) { numSentences++; } numWords++; } out.printf("%d words, %d sentences%n", numWords, numSentences); } }