/** * WordSorter1.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 WordSorter1 object reads a list of words from a file * and can print and sort the list. * * To run this program, create a text file (say words.txt). * Then execute: * * java WordSorter1 < words.txt */ import java.util.*; import java.io.*; public class WordSorter1 { private ArrayList wordList; public WordSorter1() throws IOException { String word; wordList = new ArrayList(); Scanner in = new Scanner( System.in ); while( in.hasNext() ) { word = in.next(); wordList.add( word ); } } 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( String heading ) { System.out.println( heading ); int nWords = wordList.size(); for( int k=0; k < nWords; k++ ) System.out.println( wordList.get( k ) ); System.out.println(); System.out.println(); } // 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, WordSorter1 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 WordSorter1". 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 WordSorter1 is never invoked in this context, which is as // it should be. public static void main( String[] args ) throws IOException { WordSorter1 ws = new WordSorter1(); ws.print( "---- Unsorted ----" ); ws.sort(); ws.print( "---- Sorted ----" ); } }