Hello everyone, Here I have attached program about, Simple Hangman Game using Java Program Example. The program was tested and output is shared in the same post.

HangmanGame.java

package com.javatraineronline;
import java.util.Arrays;
import java.util.Scanner;
public class HangmanGame {
public static void main(String[] args) {
// Defining the Scanner Object 
Scanner scanner = new Scanner(System.in);
// Country List for Game
String[] wordList = {"india", "america", "canada", "germany", "france", "london", "china", "japan", "australia", "italy"};
System.out.println("----------------------------------------");
System.out.println("Welcome to Hangman Game -> Country Guess");
System.out.println("----------------------------------------");
// Random number generator
int index = (int)(Math.random() * 10);
// Random word selection from array based on the generated random number
char[] mysteryWord = wordList[index].toCharArray();
char[] guess = new char[mysteryWord.length];
// Hiding the actual word with "*" symbol
for (int i = 0; i < guess.length; i++) {
guess[i] = '*';     
}
System.out.println(guess);
// Continuous loop till you when the game.
while(true) {
char playerGuess = scanner.next().charAt(0); // reading the each character from console.
for (int j = 0; j < mysteryWord.length; j++) {
if (playerGuess == mysteryWord[j]) { // Checking the matching the word with player guess
guess[j] = playerGuess;
}
}
System.out.println(guess);
// Breaking the loop based on the successful completion
if(Arrays.equals(guess, mysteryWord)) {
System.out.println("Well done");
break;
}
}
System.out.println("would like to play again ? Y/N");
char decision = scanner.next().charAt(0);
if(decision == 'y' || decision == 'Y') {
main(args); // calling the main method again based on the decision
} else {
System.out.println("Thank you !!!!");
}
scanner.close();
}
}

Output

—————————————————————————————–
Welcome to Hangman Game -> Country Guess
—————————————————————————————–
*****
i
**i**
c
c*i**
h
chi**
n
chin*
a
china
Well done
would like to play again ? Y/N
n
Thank you !!!!

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *