Skip to content
Java project #05Beginner

Hangman

Guess a programming word letter by letter before the hangman is drawn — with whole-word guesses, repeated-guess detection, ASCII art and multiple rounds.

Estimated time
~2 hours to build
Files
4 files · 425 lines
Technologies
Java 21, java.util.Random, LinkedHashSet, StringBuilder

Introduction

Hangman is a classic first game that exercises strings, sets and loops. Using a seeded java.util.Random makes every game repeatable, which is how the expected output can be tested exactly.

Problem statement

Choose a random word from a list (a seed makes the choice repeatable; 0 means random). Show the word as underscores and let the player guess letters or the whole word. Correct letters are revealed; wrong letters cost one life and wrong word guesses cost two, out of six. Repeated guesses and non-letters are reported without penalty. Draw the gallows after each guess, announce wins and losses, and offer another round; finally print the number of rounds won.

Objectives

  • Use a Set to track guesses
  • Build the masked word with StringBuilder
  • Use a seeded Random for reproducible behaviour
  • Structure a game into rounds with a method that returns the result

Features

  • Seven-stage ASCII gallows
  • Letter and whole-word guesses
  • Duplicate and invalid guesses handled gracefully
  • Multiple rounds with a final tally

Concepts demonstrated

  • Sets
  • String processing
  • Pseudo-random numbers
  • Game loops
  • Methods returning results

System architecture

main reads the seed, creates the Random and loops over rounds. playRound keeps a LinkedHashSet<Character> of guesses (which remembers the order for display) and a wrong-guess counter. Each iteration prints the gallows stage, the masked word and the guesses, checks for a win or a loss, then reads a guess. mask builds the display string by checking each letter against the set.

Folder structure

TextProject tree
hangman-game/
├── README.md
├── src/Main.java
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

src/Main.java

108 lines
Javasrc/Main.java
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
/**
* Hangman — guess the hidden word one letter at a time (or the whole word) before six wrong
* guesses. A seed makes the word choice repeatable; several rounds can be played.
*/
public class Main {
static final List<String> WORDS = List.of("variable", "inheritance", "polymorphism", "interface", "exception", "iterator", "compiler", "recursion", "algorithm", "bytecode");
static final int MAX_WRONG = 6;
static final String[] GALLOWS = {
" +---+\n |\n |\n |\n ===",
" +---+\n O |\n |\n |\n ===",
" +---+\n O |\n | |\n |\n ===",
" +---+\n O |\n /| |\n |\n ===",
" +---+\n O |\n /|\\ |\n |\n ===",
" +---+\n O |\n /|\\ |\n / |\n ===",
" +---+\n O |\n /|\\ |\n / \\ |\n ===",
};
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Seed (0 for random): ");
long seed = in.hasNextLine() ? parseLong(in.nextLine().trim()) : 0;
System.out.println();
Random rng = seed == 0 ? new Random() : new Random(seed);
int won = 0, played = 0;
do {
String word = WORDS.get(rng.nextInt(WORDS.size()));
played++;
boolean result = playRound(in, word);
if (result) won++;
System.out.print("Play again? (y/n): ");
if (!in.hasNextLine()) break;
String again = in.nextLine().trim().toLowerCase();
System.out.println(again);
if (!again.startsWith("y")) break;
} while (true);
System.out.println("\nYou won " + won + " of " + played + " round(s).");
}
static boolean playRound(Scanner in, String word) {
Set<Character> guessed = new LinkedHashSet<>();
int wrong = 0;
System.out.println("\nNew word: " + word.length() + " letters.");
while (true) {
String masked = mask(word, guessed);
System.out.println(GALLOWS[wrong]);
System.out.println("Word: " + masked + " Wrong guesses left: " + (MAX_WRONG - wrong) + " Tried: " + guessed);
if (!masked.contains("_")) {
System.out.println("You solved it: " + word.toUpperCase() + "!");
return true;
}
if (wrong == MAX_WRONG) {
System.out.println("Out of guesses. The word was " + word.toUpperCase() + ".");
return false;
}
System.out.print("Guess a letter or the word: ");
if (!in.hasNextLine()) return false;
String g = in.nextLine().trim().toLowerCase();
System.out.println(g);
if (g.length() > 1) { // a whole-word guess
if (g.equals(word)) {
for (char c : word.toCharArray()) guessed.add(c);
} else {
wrong = Math.min(MAX_WRONG, wrong + 2); // wrong word guesses cost two
System.out.println("No, it isn't '" + g + "' (-2)");
}
continue;
}
if (g.isEmpty() || !Character.isLetter(g.charAt(0))) {
System.out.println("Please type a letter.");
continue;
}
char c = g.charAt(0);
if (!guessed.add(c)) {
System.out.println("You already tried '" + c + "'.");
} else if (word.indexOf(c) >= 0) {
long count = word.chars().filter(ch -> ch == c).count();
System.out.println("Yes! '" + c + "' appears " + count + " time(s).");
} else {
wrong++;
System.out.println("No '" + c + "'.");
}
}
}
static String mask(String word, Set<Character> guessed) {
StringBuilder sb = new StringBuilder();
for (char c : word.toCharArray()) sb.append(guessed.contains(c) ? c : '_').append(' ');
return sb.toString().trim();
}
static long parseLong(String s) {
try {
return Long.parseLong(s);
} catch (NumberFormatException e) {
return 0;
}
}
}

What each file does

src/Main.java
The word list and gallows art, the round loop in playRound, and the masking helper.

How to run it

Compile

Terminal
javac -d out $(find src -name "*.java")
# Windows PowerShell: javac -d out (Get-ChildItem -Recurse src -Filter *.java).FullName

Run

Terminal
java -cp out Main

Test against the expected output

Terminal
java -cp out Main < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | java -cp out Main > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Seed (0 for random):
New word: 8 letters.
+---+
|
|
|
===
Word: _ _ _ _ _ _ _ _ Wrong guesses left: 6 Tried: []
Guess a letter or the word: e
Yes! 'e' appears 1 time(s).
+---+
|
|
|
===
Word: _ _ _ _ _ _ e _ Wrong guesses left: 6 Tried: [e]
Guess a letter or the word: a
No 'a'.
+---+
O |
|
|
===
Word: _ _ _ _ _ _ e _ Wrong guesses left: 5 Tried: [e, a]
Guess a letter or the word: e
You already tried 'e'.
+---+
O |
|
|
===
Word: _ _ _ _ _ _ e _ Wrong guesses left: 5 Tried: [e, a]
Guess a letter or the word: 3
Please type a letter.
+---+
O |
|
|
===
Word: _ _ _ _ _ _ e _ Wrong guesses left: 5 Tried: [e, a]
Guess a letter or the word: c
Yes! 'c' appears 1 time(s).
+---+
O |
|
|
===
Word: c _ _ _ _ _ e _ Wrong guesses left: 5 Tried: [e, a, c]
Guess a letter or the word: o
Yes! 'o' appears 1 time(s).
+---+
O |
|
|
===
Word: c o _ _ _ _ e _ Wrong guesses left: 5 Tried: [e, a, c, o]
Guess a letter or the word: t
No 't'.
+---+
O |
| |
|
===
Word: c o _ _ _ _ e _ Wrong guesses left: 4 Tried: [e, a, c, o, t]
Guess a letter or the word: compilr
No, it isn't 'compilr' (-2)
+---+
O |
/|\ |
|
===
Word: c o _ _ _ _ e _ Wrong guesses left: 2 Tried: [e, a, c, o, t]
Guess a letter or the word: m
Yes! 'm' appears 1 time(s).
+---+
O |
/|\ |
|
===
Word: c o m _ _ _ e _ Wrong guesses left: 2 Tried: [e, a, c, o, t, m]
Guess a letter or the word: p
Yes! 'p' appears 1 time(s).
+---+
O |
/|\ |
|
===
Word: c o m p _ _ e _ Wrong guesses left: 2 Tried: [e, a, c, o, t, m, p]
Guess a letter or the word: i
Yes! 'i' appears 1 time(s).
+---+
O |
/|\ |
|
===
Word: c o m p i _ e _ Wrong guesses left: 2 Tried: [e, a, c, o, t, m, p, i]
Guess a letter or the word: l
Yes! 'l' appears 1 time(s).
+---+
O |
/|\ |
|
===
Word: c o m p i l e _ Wrong guesses left: 2 Tried: [e, a, c, o, t, m, p, i, l]
Guess a letter or the word: r
Yes! 'r' appears 1 time(s).
+---+
O |
/|\ |
|
===
Word: c o m p i l e r Wrong guesses left: 2 Tried: [e, a, c, o, t, m, p, i, l, r]
You solved it: COMPILER!
Play again? (y/n): y
New word: 9 letters.
+---+
|
|
|
===
Word: _ _ _ _ _ _ _ _ _ Wrong guesses left: 6 Tried: []
Guess a letter or the word: z
No 'z'.
+---+
O |
|
|
===
Word: _ _ _ _ _ _ _ _ _ Wrong guesses left: 5 Tried: [z]
Guess a letter or the word: q
No 'q'.
+---+
O |
| |
|
===
Word: _ _ _ _ _ _ _ _ _ Wrong guesses left: 4 Tried: [z, q]
Guess a letter or the word: x
Yes! 'x' appears 1 time(s).
+---+
O |
| |
|
===
Word: _ x _ _ _ _ _ _ _ Wrong guesses left: 4 Tried: [z, q, x]
Guess a letter or the word: j
No 'j'.
+---+
O |
/| |
|
===
Word: _ x _ _ _ _ _ _ _ Wrong guesses left: 3 Tried: [z, q, x, j]
Guess a letter or the word: w
No 'w'.
+---+
O |
/|\ |
|
===
Word: _ x _ _ _ _ _ _ _ Wrong guesses left: 2 Tried: [z, q, x, j, w]
Guess a letter or the word: k
No 'k'.
+---+
O |
/|\ |
/ |
===
Word: _ x _ _ _ _ _ _ _ Wrong guesses left: 1 Tried: [z, q, x, j, w, k]
Guess a letter or the word: v
No 'v'.
+---+
O |
/|\ |
/ \ |
===
Word: _ x _ _ _ _ _ _ _ Wrong guesses left: 0 Tried: [z, q, x, j, w, k, v]
Out of guesses. The word was EXCEPTION.
Play again? (y/n): n
You won 1 of 2 round(s).
Input
7
e
a
e
3
c
o
t
compilr
m
p
i
l
r
y
z
q
x
j
w
k
v
n

Testing

  • Run with tests/sample-input.txt and compare with tests/expected-output.txt.
  • Seed 7 chooses COMPILER first; a wrong word guess (compilr) costs two lives, and the player still wins.
  • The second round (EXCEPTION) is lost after six wrong letters.
  • The final line reads 'You won 1 of 2 round(s).'

Common errors

The same word appears every game

Enter 0 for the seed to use an unseeded Random.

Guessing 'E' doesn't reveal 'e'

Lower-case every guess before comparing.

Possible improvements

  • Load words from a file and pick by difficulty
  • Give a hint after four wrong guesses
  • Add a two-player mode where one player types the word

Additional challenges

  1. 1Show the alphabet with used letters crossed out.
  2. 2Score rounds by remaining lives.
  3. 3Implement 'evil hangman', which changes the word to avoid the player's guesses.

Built and tested it yourself? Mark it to update your dashboard.