/** * WordCounter.java * * @author Jeff Ondich * @version 10/5/05 * * Counts the words in the file specified on the command line. * This one uses a word-cleaning method to strip punctuation and other * wacky characters. */ import java.util.*; import java.io.*; public class WordCounter { public static void main( String[] args ) throws FileNotFoundException { if( args.length != 1 ) { System.err.println( "Usage: java WordCounter filename" ); return; } int nWords = 0; Scanner in = new Scanner( new File( args[0] ) ); while( in.hasNext() ) { String word = cleanWord( in.next() ); if( word.length() > 0 ) { nWords++; System.out.println( word ); } } System.out.println(); System.out.println( "There were " + nWords + " words in the input." ); } public static String cleanWord( String dirtyWord ) { String cleanWord = ""; int length = dirtyWord.length(); for( int k=0; k < dirtyWord.length(); k++ ) { char ch = dirtyWord.charAt( k ); if( Character.isLetter( ch ) || ch == '-' || ch == '\'' ) cleanWord = cleanWord + ch; } return cleanWord; } }