import java.util.Scanner; import java.io.*; /** * CS151 Fall 2007 Lab 12 Solution. 0) // use supplied argument filename = args[0]; else { // get filename from user System.out.print("Enter name of file to read: "); filename = terminal.next(); } // variable to know when the file has been successfully opened and to exit while loop boolean fileNameOK = false; // try to open file and if unsuccessful keep prompting user for name and // tyring to open until successfull while (!fileNameOK) { try { // try to create a connection/open it reader = new FileReader(filename); // if file opened without error this line is reached and will exit the loop fileNameOK = true; } catch(FileNotFoundException exception) { System.out.println("Couldn't open file " + filename + "."); System.out.print("Enter name of file to read: "); // get name of file from the user filename = terminal.next(); } } // attach a scanner to the successfully opened file Scanner input = new Scanner(reader); // declare and initialize line, word, and character counters int numLines = 0; int numWords = 0; int numChars = 0; // Keep reading ta line of the file incrementing the counts until there are no lines left while (input.hasNextLine()) { // a variable store the contents of the current line String line = input.nextLine(); numLines++; numChars += line.length(); // get number of words by splitting and checking length of resulting array numWords += line.split(" ").length; } // Display the final counts System.out.println("File " + filename + " contains " + numLines + " lines, " + numWords + " words, and " + numChars + " characters."); // nicely close the Scanner and file being read input.close(); } }