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.
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.
*****. There are no matching letters.
H****. There’s an
H, and it’s in the right position.
*++**. There are an
O, but they’re in the wrong positions.
The full class
Here’s the working solution that I came up with.
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
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.