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.

image

image

public class HiddenWord {
    private static String word = "";
    HiddenWord(String hidden) {
        word = hidden;
    }

    public static String getHint(String guess) {
        String hint = "";
        for (int i=0; i<word.length(); i++) {
            for (int j=0; j<word.length(); j++) {//uses nested for loop to see if each letter in guess is the same as one in secret word
                if (i==j && guess.charAt(i)==word.charAt(j)) {// if chars are same at the same place, character at that index is the character
                    hint+=guess.charAt(i);
                    break;
                } else if (i!=j && guess.charAt(i)==word.charAt(j)) {//if chars are the same but in different positions, character at that index is "+"
                    hint+="+";
                    break;
                } else if (j==word.length()-1) {// otherwise, character at that index is "*"
                    hint+="*";
                }
            }
        }
        return hint;
    }
}
public class Test2 {
    public static void main(String[] args) {
        HiddenWord puzzle = new HiddenWord("HARPS");
        System.out.println(puzzle.getHint("AAAAAA"));
        System.out.println(puzzle.getHint("HELLO"));
        System.out.println(puzzle.getHint("HEARTS"));
        System.out.println(puzzle.getHint("HARMS"));
        System.out.println(puzzle.getHint("HARPS"));
    }
}
Test2.main(null);
+A+++
H****
H*++*
HAR*S
HARPS
  • FRQ Type: Classes
  • How main algorithm shows FRQ type:

This FRQ involves using classes. To complete the FRQ, we must use classes and their associated features, like instance variables, constructors, and more. Using these features, we must evaluate the guess that the user inputs, and determine how close it is to the secret word. First, we initialize a new object, with the secret word. Then, we determine which letters in the guess are present and in the right place in the secret word, and we assign the correct symbol to the result.