Question 2

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.

If the letter in the guess is … the corresponding character in the hint is
also in the same position in the hidden word the matching letter
also in the hidden word, but in different position “*”
not in the hidden word ”+”

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.

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”
public class HiddenWord {
    private String hiddenWord;
    public HiddenWord(String hiddenWord) {
        this.hiddenWord = hiddenWord;
    }
    public String getHint(String guess) {
        String hint = "";
        for (int i = 0; i < guess.length(); i++) {
            if (guess.charAt(i) == hiddenWord.charAt(i)) {
                hint = hint + guess.charAt(i);
            } else if (hiddenWord.indexOf(guess.charAt(i)) != -1) {
                hint = hint + "+";
            } else {
                hint = 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"));
    }
}
HiddenWord.main(null);
+A+++
H****
H*++*
HAR*S
HARPS

Reflection

This FRQ was based on classes. When I first read this question, I thought it would be hard to solve. But while solving, I realized that the only problem I had was using the indexOf and charAt methods because I knew that Strings had those methods but I forgot what the methods were exactly. After searching them up, I was able to solve this problem much quicker than I believed. Overall, this FRQ helped me realize that I generally need help with the Java built-in methods because I tend to forget the format. I also need a bit more help with classes because sometimes it troubles me.