Stanford CS106A Hangman Game Lexicon Solution

Wohoo! I am officially done with the Hangman game, and I did it all on my own. I am starting to suspect that the first part of the class is really difficult to weed out the non-serious students. Now that I got past the Breakout game, everything seems to be a lot more straightforward. The last part of the Hangman Game is to import a much longer list of words from the HangmanLexicon.txt file. The instructions for this part of the game are as follows:

Here is my solution:

If you watch Lectures 15 and 16, this problem becomes pretty straight-forward. You can also find my solution on gist.

 * File:
 * -------------------------
 * This file contains a stub implementation of the HangmanLexicon
 * class that you will reimplement for Part III of the assignment.

import acm.util.*;
import java.util.*;

public class HangmanLexicon {

	private ArrayList <String> wordList = new ArrayList <String> ();	

	public HangmanLexicon() {
	//adds the individual words in the file to the array list
		try {
			BufferedReader hangmanWords = new BufferedReader(new FileReader("HangmanLexicon.txt"));
			while(true) {
				String line = hangmanWords.readLine();
				if(line == null) break;
		} catch (IOException ex) {
			throw new ErrorException(ex);

/** Returns the word at the specified index. */
	public String getWord(int index) {
		return wordList.get(index);


	/** Returns the number of words in the lexicon. */
	public int getWordCount() {
		return wordList.size();

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.

  • James

    Wow, your code for this section is waay more compact than mine ended up. Partly bc I didn’t understand arrayLists, so setting up the array was painful… anyway. The only thing I’m not understanding in your code are the expressions < &gt.

    • Hey James,

      That’s the “greater than” sign. When I embed the code into WordPress, it changes greater than to &gt

  • Dustin

    I’m trailing you by a year and a half, but I just finished this game! The only downside is I feel like I spent a ton of time on such an insignificant program :/

    • Haha, that is college for you 🙂 Very theoretical and not as applicable to the real world.

      I really liked CS106A, because it taught me some of the most important skills as a programmer – how to be persistent, how to debug, and how to think like a programmer. That said, there are other courses out there that are more practical if you feel like you’re not learning much from this one.

      • Dustin

        Thanks for your reply. I am just using this as an introduction to programming, and it is going well so far I think. I guess I was just feeling a moment of despair. I just finished Yahtzee and I can’t wait to get through the rest!