/** * WordSorter3.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 WordSorter3 object reads a list of words from a file * and can print and sort the list. */ import java.util.*; import java.io.*; public class WordSorter3 { ArrayList wordList; PrintStream outFile; public WordSorter3( String inFileName, String outFileName ) throws IOException { // Open the output file and store the reference so we can // write to the file later. outFile = new PrintStream( new File( outFileName ) ); // Open the input file and load its contents into wordList. String line; wordList = new ArrayList(); Scanner fileScanner = new Scanner( new File( inFileName ) ); while( fileScanner.hasNext() ) { line = fileScanner.nextLine(); wordList.add( 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( String heading ) { outFile.println( heading ); int nWords = wordList.size(); for( int k=0; k < nWords; k++ ) outFile.println( wordList.get( k ) ); outFile.println(); outFile.println(); } public static void main( String[] args ) throws IOException { Scanner in = new Scanner( System.in ); System.out.print( "Input file? " ); String inFileName = in.next(); System.out.print( "Output file? " ); String outFileName = in.next(); WordSorter3 ws = new WordSorter3( inFileName, outFileName ); ws.print( "---- Unsorted ----" ); ws.sort(); ws.print( "---- Sorted ----" ); } }