// Word count. Usage: java Wc filename // Print each word in filename on a separate line in upper // case characters. Then print a count of the number of words. // A word is any sequence of letters separated by other characters. import java.io.*; class Wc { public static void main(String argv[]) { // Open the input file, report errors try { // Open input file. Errors are caught below InputStream f=new FileInputStream(argv[0]); // Count words int c; // Current character boolean last_char_was_letter=false; // Previous character type int count=0; // Number of words while ((c=f.read())>=0) { // Until -1 (EOF) if (Character.isLetter((char)c)) { c=Character.toUpperCase((char)c); if (!last_char_was_letter) { last_char_was_letter=true; ++count; } System.out.write(c); } else if (last_char_was_letter) { last_char_was_letter=false; System.out.write('\n'); } } // Print result System.out.println(argv[0]+" has "+count+" words"); // Close file f.close(); } catch(FileNotFoundException x) { System.out.println("File not found: "+argv[0]); } catch(ArrayIndexOutOfBoundsException x) { // for argv System.out.println("Usage: java Wc filename"); } catch(IOException x) { // Other exception, print it System.out.println(""+x); } } }