Java Reference
In-Depth Information
Figure 10.3 gives the code for the constructor. It merely opens and reads
the two files corresponding to the grid and the word list. The supporting rou-
tine openFile , shown in Figure 10.4, repeatedly prompts for a file until an open
is successful. The readWords routine, shown in Figure 10.5, reads the word list.
The constructor
opens and reads
the data files. We
skimp on error
checks for brevity.
1 /**
2 * Constructor for WordSearch class.
3 * Prompts for and reads puzzle and dictionary files.
4 */
5 public WordSearch( ) throws IOException
6 {
7 puzzleStream = openFile( "Enter puzzle file" );
8 wordStream = openFile( "Enter dictionary name" );
9 System.out.println( "Reading files..." );
10 readPuzzle( );
11 readWords( );
12 }
figure 10.3
The WordSearch
class constructor
1 /**
2 * Print a prompt and open a file.
3 * Retry until open is successful.
4 * Program exits if end of file is hit.
5 */
6 private BufferedReader openFile( String message )
7 {
8 String fileName = "";
9 FileReader theFile;
10 BufferedReader fileIn = null;
11
12 do
13 {
14 System.out.println( message + ": " );
15
16 try
17 {
18 fileName = in.readLine( );
19 if( fileName == null )
20 System.exit( 0 );
21 theFile = new FileReader( fileName );
22 fileIn = new BufferedReader( theFile );
23 }
24 catch( IOException e )
25 { System.err.println( "Cannot open " + fileName ); }
26 } while( fileIn == null );
27
28 System.out.println( "Opened " + fileName );
29 return fileIn;
30 }
figure 10.4
The openFile routine
for opening either the
grid or word list file
Search WWH ::




Custom Search