Hangman Game in Java

Hangman is a popular guessing game in which the player has to guess a word by suggesting letters one at a time. The player is given a limited number of attempts, typically six, to guess the word correctly.

To implement Hangman in Java, you can start by choosing a random word from a list of words, and then display a series of asterisks to represent each letter in the word. The player can then guess a letter and if the letter is present in the word, the corresponding asterisks in the displayed word are replaced with the guessed letter. If the player guesses incorrectly, the number of attempts is decremented. If the player correctly guesses all the letters in the word before they run out of attempts, they win the game.

Here's a basic implementation of Hangman in Java:


import java.util.Scanner;

public class Hangman {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] words = {"java", "python", "ruby", "javascript", "php"}; // List of words to choose from
        String word = words[(int) (Math.random() * words.length)]; // Choose a random word from the list
        String asterisk = new String(new char[word.length()]).replace("\0", "*");
        int attempts = 0;

        while (attempts < 6 && asterisk.contains("*")) { // Player has 6 attempts to guess the word
            System.out.println("Guess a letter: ");
            System.out.println(asterisk);
            String guess = scanner.next();
            if (word.contains(guess)) {
                StringBuilder stringBuilder = new StringBuilder(asterisk);
                for (int i = 0; i < word.length(); i++) {
                    if (word.charAt(i) == guess.charAt(0)) {
                        stringBuilder.setCharAt(i, guess.charAt(0));
                    }
                }
                asterisk = stringBuilder.toString();
            } else {
                attempts++;
            }
        }
        if (attempts == 6) {
            System.out.println("Sorry, you lose. The word was " + word);
        } else {
            System.out.println("Congratulations, you win! The word was " + word);
        }
    }
}
Input & Output
Guess a letter: 
****
a
Guess a letter: 
*a*a
j
Guess a letter: 
ja*a
v
Congratulations, you win! The word was java
Next Post Previous Post
No Comment
Add Comment
comment url