cs106a – Assignment #4 – Task #3

The complete specification of assignment #4 can be found as part of the stream at iTunes.

Reading the lexicon from a data file

Part III of this assignment is by far the easiest and requires considerably less than half a page of code.
Your job in this part of the assignment is simply to reimplement the HangmanLexicon class so that instead of selecting from a meager list of ten words, it reads a much larger word list from a file. The steps involved in this part of the assignment are as follows:

  1. Open the data file HangmanLexicon.txt using a BufferedReader that will allow you to read it line by line.
  2. Read the lines from the file into an ArrayList.
  3. Reimplement the getWordCount and getWord methods in HangmanLexicon so that

they use the ArrayList from step 2 as the source of the words.
The first two steps should be done in a constructor for HangmanLexicon, which you will need to add to the file. The last step is simply a matter of changing the implementation of the methods that are already there.
Here is how the HangmanLexicon constructor should be added to the HangmanLexicon class:

public class HangmanLexicon {
   // This is the HangmanLexicon constructor
   public HangmanLexicon() {
      // your initialization code goes here
   }
   // rest of HangmanLexicon class...
}

Note that nothing in the main program should have to change in response to this change in the implementation of HangmanLexicon. Insulating parts of a program from changes in other parts is a fundamental principle of good software design.

Open the file, create a new ArrayList and add each line to the list:

	public HangmanLexicon() {
		try {
			BufferedReader rd = new BufferedReader(
					new FileReader(DATA_FILE)
			);
			
			wordList = new ArrayList<String>();
			
			while (true) {
				String line = rd.readLine();
				if (line == null) break;
				if (!wordList.contains(line)) {
					wordList.add(line);
				}
			}
		} catch (IOException ex) {
			throw new ErrorException(ex);
		}
	}

Then return the size of the list, or the indexed word respectively:

	public int getWordCount() {
		return wordList.size();
	}

	public String getWord(int index) {
		return wordList.get(index);
	};

The code for this assignment is available on github.

FacebooktwitterredditpinterestlinkedintumblrmailFacebooktwitterredditpinterestlinkedintumblrmail

Leave a Reply

Your email address will not be published.