Hidden Word Java Program

Hidden Word Java Program | The Hidden Word is a guessing game where the player guesses a hidden word. The given hidden word contains only capital letters and the length of the hidden word will be known to the player. A guess word also contains capital letters and the same length as a hidden word.

After the guess is made, based on the comparison of the guess word and the hidden word, the player will be given a hint. Every position in the hint contains the characters corresponding to the letter in the same position in the guess word.  The following rules determine the characters that appear in the hint.

If the letter in the guess word is…The corresponding character in the hint will be…
Also in the same position in the hidden word,The matching letter
Also in the hidden word, but in a different position,“+”
Not in the hidden word, “*”

Observe the below table to understand in detail
Let the hidden word be:- “HARPS”.
Declared as,
HiddenWord puzzle = new HiddenWord(“HARPS”);

Calling getHint() method:-The string which can be returned:-
puzzle.getHint(“AAAAA”)+A+++
puzzle.getHint(“HELLO”)H****
puzzle.getHint(“HEART”)H*++*
puzzle.getHint(“HARMS”)HAR*S
puzzle.getHint(“HARPS”)HARPS

Hidden Word Java Program Demonstration

Let us write the complete hidden word class. We will take a private instance variable to store the word. And we will declare a constructor to create the object. The getHint() method takes the guess string and returns the hint string based on the above-given rules.

Hidden Word Java Program

public class HiddenWord {
   private String word;

   public HiddenWord(String word) {
      this.word = word;
   }

   public String getHint(String guess) {
      String hint = "";

      for (int i = 0; i < word.length(); i++) {
         String guessLetter = guess.substring(i, i + 1);
         if (word.substring(i, i + 1).equals(guessLetter)) {
            hint += guessLetter;
         } else if (word.indexOf(guessLetter) != -1) {
            hint += "+";
         } else {
            hint += "*";
         }
      }

      return hint;
   }

   public static void main(String[] args) {
      HiddenWord puzzle = new HiddenWord("HARPS");
      System.out.println(puzzle.getHint("AAAAA"));
      System.out.println(puzzle.getHint("HELLO"));
      System.out.println(puzzle.getHint("HEART"));
      System.out.println(puzzle.getHint("HARMS"));
      System.out.println(puzzle.getHint("HARPS"));
   }
}

Output:

+A+++
H****
H*++*
HAR*S
HARPS

In the HiddenWord class, we have taken a constructor to instantiate the object. On this created object we have called getHint() method. The getHint() method returns the guess word according to the rule. Also see:- Monty Hall Java Program

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.