# Hidden Word Solution

Creating a full class has been a popular free response question for the past few years on the AP Computer Science exam. In 2015 they asked you to create a class called HiddenWord that mimicked a word guessing game. A few years somebody would create Wordle, which is pretty much the same game.

The idea was that the computer knew a word and you tried to guess it. The computer would then take your guess and compare it to the answer. If you guess had the same letter in the same position, that letter was returned in the clue. If your guess had a matching letter, but in the wrong spot the clue would contain a + in that position. And if the letter doesn’t exist, a * would be in that position.

For example, let’s say that the answer word was `HELLO`. Here are a few guesses and what they would return.

`ABCDF` would return `*****`. There are no matching letters. `HOWDY` would return `H****`. There’s an H, and it’s in the right position. `THOSE` would return `*++**`. There are an H and an O, but they’re in the wrong positions. `HELPS` would return `HEL**`. `HELLO` would return `HELLO`

## The full class

Here’s the working solution that I came up with.

``````public class HiddenWord {
private String word;

public HiddenWord(String w) {
word = w;
}

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

for (int i=0; i<guess.length(); i++) {
String guessCharacter = guess.substring(i, i+1);
String wordCharacter = word.substring(i, i+1);
if (guessCharacter.equals(wordCharacter)) {
out += guessCharacter;
}
else if (word.indexOf(guessCharacter) >= 0) {
out += "+";
}
else {
out += "*";
}
}

return out;
}
}
``````

You have to know to use `public class HiddenWord` to define a class named `HiddenWord`. For the AP exam, classes are public.

There needs to be an instance variable to hold the answer, and it needs to be a `String`. I named mine `word`. And it should be `private`.

The problem gave an example constructor call where the answer string was passed in. It looked something like this – `HiddenWord game = new HiddenWord("HELLO");`. That tells us that our constructor must take exactly one `String` parameter.

And you have to implement a method called `getHint` that also takes a `String` parameter. `guess` would then be compared to `word` looking at each character. If the characters are an exact match, that character it put into `out`. If they don’t match, but the character from `guess` is somewhere in `word` then a `+` symbol is put into `out`. And if neither is `true` then a `*` is put into `out`.

This site contains affiliate links. If you click an affiliate link and make a purchase we may get a small commission. It doesn't affect the price you pay, but it is something we must disclose.