Hangman Game in Java (With Explanation)
This document contains a simple Hangman game written in Java along with a step-by-step
explanation.
Java Code:
import [Link].*;
public class Hangman {
public static void main(String[] args) {
String[] words = {"python", "programming", "hangman", "developer", "computer"};
Random random = new Random();
String word = words[[Link]([Link])];
char[] guessedWord = new char[[Link]()];
[Link](guessedWord, '_');
List<Character> guessedLetters = new ArrayList<>();
int attempts = 6;
Scanner scanner = new Scanner([Link]);
[Link]("Welcome to Hangman!");
while (attempts > 0 && new String(guessedWord).contains("_")) {
[Link]("\nWord: " + [Link](guessedWord));
[Link]("Guessed letters: " + guessedLetters);
[Link]("Attempts left: " + attempts);
[Link]("Enter a letter: ");
char guess = [Link]().toLowerCase().charAt(0);
if ([Link](guess)) {
[Link]("You already guessed that letter!");
continue;
}
[Link](guess);
if ([Link](guess) >= 0) {
for (int i = 0; i < [Link](); i++) {
if ([Link](i) == guess) {
guessedWord[i] = guess;
}
}
[Link]("Correct guess!");
} else {
attempts--;
[Link]("Wrong guess!");
}
}
if (!new String(guessedWord).contains("_")) {
[Link]("\nCongratulations! You guessed the word: " + word);
} else {
[Link]("\nGame Over! The word was: " + word);
}
[Link]();
}
}
Explanation:
1. A list of words is stored in an array.
2. A random word is selected using Random class.
3. A character array is used to display blanks (_).
4. ArrayList stores guessed letters.
5. The player has 6 attempts.
6. A loop runs until the word is guessed or attempts run out.
7. The program checks if the guessed letter exists in the word.
8. If correct, the guessed word updates.
9. If wrong, attempts decrease.
10. The game ends with a win or loss message.