- 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.
Guess Letter | Hint Character |
---|---|
In same position and also in hidden word | Matching letter |
In hidden word, but in different position | “*” |
Not in hidden word | ”+” |
Instructions:
- 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.
Example:
Suppose the variable puzzle
is declared as follows:
The following table shows several guesses and the hints that would be produced:
Call to getHint |
String returned |
---|---|
puzzle.getHint(“AAAAA”) | “+A+++” |
puzzle.getHint(“HELLO”) | “H**” |
puzzle.getHint(“HEART”) | “H++” |
puzzle.getHint(“HARMS”) | “HAR*S” |
puzzle.getHint(“HARPS”) | “HARPS” |
This table demonstrates the correspondence between the guess and the hint produced by the getHint
method based on the hidden word.
Reflection.
- THis was where I found most of my suceses in and was the question I was most undrstood as it tested my ability to create a class with approprate fields and instance vairable, constructors that intialized my variables and methods that created the matching game, however I had to reference previous lessons to understand the implementation of a string builder to add the correct vairables to match up the guess
public class HiddenWord {
private String hiddenWord;
public HiddenWord(String word) {
this.hiddenWord = word;
}
public String getHint(String guess) {
StringBuilder hint = new StringBuilder();
for (int i = 0; i < hiddenWord.length(); i++) {
if (guess.charAt(i) == hiddenWord.charAt(i)) {
hint.append(hiddenWord.charAt(i)); // Correct letter in correct position
} else if (hiddenWord.indexOf(guess.charAt(i)) != -1) {
hint.append("+"); // Correct letter but in wrong position
} else {
hint.append("*"); // Incorrect letter
}
}
return hint.toString();
}
public static void main(String[] args){
// test data
HiddenWord harps = new HiddenWord("HARPS");
System.out.println(harps.getHint("HEART"));
System.out.println(harps.getHint("HELLO"));
System.out.println(harps.getHint("HARPS"));
}
}
HiddenWord.main(null);
H*++*
H****
HARPS