Consider a guessing game in which a player tries to guess a hidden word. The hidden word contains only capital letters and has a length known to the player. A guess contains only capital letters and has the same length as the hidden word.
After a guess is made, the player is given a hint that is based on a comparison between the hidden word and the guess. Each position in the hint contains a character that corresponds to the letter in the same position in the guess. The following rules determine the characters that appear in the hint.
The HiddenWord class will be used to represent the hidden word in the game. The hidden word is passed to the constructor. The class contains a method, getHint, that takes a guess and produces a hint.
For example, suppose the variable puzzle is declared as follows.
HiddenWord puzzle = new HiddenWord(“HARPS”);
The following table shows several guesses and the hints that would be produced.
Write the complete HiddenWord class, including any necessary instance variables, its constructor, and the method, getHint, described above. You may assume that the length of the guess is the same as the length of the hidden word.
public class HiddenWord {
private String word;
public HiddenWord(String word) {
this.word = word;
}
public String getHint(String guess) {
StringBuilder hint = new StringBuilder();
for (int i = 0; i < word.length(); i++) { // iterate over each character in the guess string
// get the guessed letter at position i
char guessedLetter = guess.charAt(i);
// get the corresponding actual letter from the word at position i
char actualLetter = word.charAt(i);
if (guessedLetter == actualLetter) {
hint.append(actualLetter); // matched letter
} else if (word.indexOf(guessedLetter) != -1) {
hint.append('+'); // letter exists but not same position
} else {
hint.append('*'); // letter not in hidden word
}
}
return hint.toString();
}
public static void main(String[] args) {
// hidden word from College Board
HiddenWord puzzle = new HiddenWord("HARPS");
// testing calls to get hints
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"));
}
}
HiddenWord.main(null);
+A+++
H****
H*++*
HAR*S
HARPS