/** * WordSorter.java * * @author Jeff Ondich * @version 2/23/05 * * Illustrates three new concepts: ArrayList, file input, * and the use of main() as a unit test. * * A WordSorter object reads a list of words from a file * and can print and sort the list. */ import java.util.*; import java.io.*; public class WordSorter { ArrayList wordList; public WordSorter( String fileName ) throws IOException { String line; wordList = new ArrayList(); Scanner fileScanner = new Scanner( new File( fileName ) ); while( fileScanner.hasNext() ) { line = fileScanner.nextLine(); wordList.add( (String)line ); } } public void sort() { int j, k; for( j=1; j < wordList.size(); j++ ) { String temp = wordList.get( j ); for( k=j-1; k >= 0 && temp.compareTo( wordList.get( k ) ) < 0; k-- ) { wordList.set( k+1, wordList.get( k ) ); } wordList.set( k + 1, temp ); } } public void print() { int nWords = wordList.size(); for( int k=0; k < nWords; k++ ) { System.out.println( wordList.get( k ) ); } } // When you have a class that you intend to instantiate in a complex program, // it's a good idea to write some testing code that tests just the features // of your class. For example, WordSorter might easily get used in a more // complex program. Yet we should definitely test its features (sort and print, // in particular) in isolation to ferret out local bugs. This testing of a // small piece of code in isolation from the larger system it's in is called // "unit testing". // // A great place to put unit testing code for a Java class is in main within // the class itself. Thus, if you want to run the unit test, you use // the command "java WordSorter". But if you have a bigger program, you // might write a class called "BigWordProgram" with its own main method, // and then invoke the bigger program via "java BigWordProgram". The // unit test for WordSorter is never invoked in this context, which is as // it should be. public static void main( String[] args ) throws IOException { if( args.length == 0 ) { System.out.println( "Usage: java WordSorter wordFile" ); return; } WordSorter ws = new WordSorter( args[0] ); System.out.println( "---- Unsorted ----" ); ws.print(); System.out.println( "\n\n---- Sorted ----" ); ws.sort(); ws.print(); } }