Java practice: hangman

Soumya
4 min readAug 21, 2022

Let’s create a simple program that allows users to play hangman against the computer.

Here’s how the program is going to work:

The computer thinks of a word. The user tries to guess the word by trying a letter at a time or trying a word. If the letter is in the computer’s word, then the computer shows the user where it fits. This continues until either the user runs out of guesses or the user guesses the word.

First in a class called Hangman, I will create a method that will convert a word to its representation in dashes. This way, the user will be able to see how many letters the computer’s word has. Later on, these dashes will be replaced by the letters when the user guesses correctly.

private String transformToUnderscores(String s) {
String dashes = "";
for (int i = 0; i < s.length(); i++) {
dashes += "-";
}
return dashes;
}

Next, I will create a method that will get a random word from a text file. I have saved a list of six-letter words in a file called “words.txt”. One word is on each line.

A list of words from which a random word is to be chosen is saved in words.txt

readFileAndGetRandomWord() will go through each line in the file and pick a random word to return. I’m using try-with-resources so that the FileReader and BufferedReader resources are automatically closed after use.

private String readFileAndGetRandomWord(String filename) {
//try-with-resources
try (FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr)) {
List<String> lines = new ArrayList<String>(); String line = br.readLine(); while (line != null) {
lines.add(line);
line = br.readLine();
}
String randomWord = lines.get(new Random().nextInt(lines.size())); return randomWord.toLowerCase(); } catch (IOException ex) {
}
//return default word if there is a problem with reading the file
return "coding";
}

Now, I can declare instance variables and create a constructor. I’m using the readFileAndGetRandomWord() method to first set the word the computer is thinking of. Then, I convert it into its representation with underscores so that it can be displayed to the user. I also set the maximum number of guesses to 10.

private Scanner in;
private final String WORD;
private final int maxNumGuesses;
private String display;
public Hangman() {
in = new Scanner(System.in);
WORD = readFileAndGetRandomWord("words.txt");
maxNumGuesses = 10;
display = transformToUnderscores(WORD);
}

Here’s the method used to obtain a guess from the user. The guess can be a letter or a word.

private String getGuessFromUser() {
String w = in.next().toLowerCase();
return w;
}

I will need a method to replace dashes with a given letter.

private String replaceIfLetterIsCorrect(String c, String wordRepresentation) {
String output = wordRepresentation;
for (int i = 0; i < WORD.length(); i++) {
if (WORD.charAt(i) == c.charAt(0)) {
output= output.substring(0,i) + c + output.substring(i+1);
}
}
return output;
}

Now, I can put this all together in the play() method.

private void play() {
System.out.println("You have " + maxNumGuesses + " guesses");
String guess = ""; //this will store the user's guess
int guessNum = 0; //which guess the user is on while (true) {
//display computer's word with dashes to hide letters not yet guessed
System.out.println("The word: " + display);
//end game if max number of guesses has been reached
if (guessNum == maxNumGuesses) {
System.out.println("\\nGAME OVER\\nThe word was " + WORD);
break;
}
//prompt user to provide guess
System.out.print((guessNum + 1) + ". Enter a letter or a word (enter 0 to end the game): ");
guess = getGuessFromUser(); //allow user to exit game by pressing 0
if (guess.equals("0")) {
break;
}
if (guess.length()==0) { //ignore if user just presses enter
continue;
} else if (guess.length() > 1) { //user has guessed a word
//if guess is equal to the computer's word then user has won
if (guess.equals(WORD)) {
System.out.println("You guessed correctly!");
break;
}
} else { //user has guessed a letter
//change the display if guess is correct
display = replaceIfLetterIsCorrect(guess, display);
//if all letters have been guessed then user has won
if (display.equals(WORD)) {
System.out.println("You guessed correctly!");
break;
}
}
guessNum += 1; // increase the guess count }
System.out.println("Bye!");
}

Finally, I’ll call the play() method in the main() method.

public static void main(String[] args) {
System.out.println("Let's play a game of hangman! \\n");
new Hangman().play();
}

This is what a typical game would look like:

This is a simple program. Here are some suggestions for improvement to make the program more complex:

  • use an API to get random words instead of storing words in a file
  • make it so that the user cannot guess a letter/word multiple times
  • make a hangman drawing to show progress

Feel free to reach out to me for a chat or if you have any questions/comments/suggestions :)

--

--

Soumya

Budding software developer passionate about all things mobile