/** * Dictionary.java * * This class provides a searchable word list, plus a primitive * spelling-correction facility. Its constructor takes the name * of an alphabetized file of words, one word per line, as a * parameter. * * This class is part of an exercise on profiling, and thus has * been left intentionally in a non-optimal state. */ import java.util.*; import java.io.*; public class Dictionary { private ArrayList mWords; public Dictionary( String fileName ) { mWords = new ArrayList(); try { Scanner in = new Scanner( new File( fileName ) ); while( in.hasNext() ) mWords.add( in.next() ); } catch( IOException e ) { System.err.println( e.getMessage() ); } } /** * Returns true if the specified string is in the dictionary's * word list, and false otherwise. Case-insensitive. */ public boolean isWord( String s ) { for( int k=0; k < mWords.size() && s.toLowerCase().compareTo( mWords.get( k ) ) <= 0; k++ ) { if( s.toLowerCase().equals( mWords.get( k ) ) ) return true; } return false; } /** * Returns the word in the dictionary word list that is "closest" * to the specified string. Closeness is determined by the * stringDistance method. */ public String getClosestMatch( String s ) { if( mWords.size() == 0 ) return ""; String t = s.toLowerCase(); int indexOfClosestMatch = 0; int closestDistance = stringDistance( t, (String)mWords.get( 0 ) ); for( int k=1; k < mWords.size(); k++ ) { int distance = stringDistance( t, (String)mWords.get( k ) ); if( distance < closestDistance ) { closestDistance = distance; indexOfClosestMatch = k; } } return (String)mWords.get( indexOfClosestMatch ); } /** * Returns the "distance" between the specified strings. * Though the real spelling-correction action is right * here, in the present context, it doesn't really matter * how we define distance, so a simple-minded approach is * used here. */ private static int stringDistance( String a, String b ) { int distance = 0; int k; for( k=0; k < a.length(); k++ ) { if( k >= b.length() || a.charAt( k ) != b.charAt( k ) ) distance++; } if( k < b.length() ) distance += (b.length() - k); return distance; } }