Question 2

HiddenWord puzzle = new HiddenWord(“HARPS”);

The following table shows several guesses and the hints that would be produced.

Screenshot 2024-02-22 at 12 09 14 PM

Write the complete HiddenWord class, including any necessary instance variables, its constructor, and the method, getHint, described above. You may assume that the length of the guess is the same as the length of the hidden word.*

public class HiddenWord {
    private String word;

    // contrucotr, initialize hidden word
    public HiddenWord(String hWord) {
        word = hWord;
    }

    // method, makes hint based on guess
    public String getHint(String guess) {
        // makes the hint
        StringBuilder hint = new StringBuilder();
        // looping through each letter in guess word
        for (int i = 0; i < guess.length(); i++) {
            String guessLetter = guess.substring(i, i + 1);
            String hiddenLetter = word.substring(i, i + 1);

            if (guessLetter.equals(hiddenLetter)) {
                // right letter right position
                hint.append(guessLetter); 
            } else if (word.contains(guessLetter)) {
                // right letter wrong position
                hint.append('+'); 
            } else {
                // wrong letter
                hint.append('*'); 
            }
        }
        return hint.toString();
    }

    // testing the class
    public static void main(String[] args) {
        HiddenWord puzzle = new HiddenWord("GAMING");

        // testing through guesses
        String[] guesses = {"GHOSTS", "THANKS", "GAMBIT", "GAMBLE", "GAMING"};
        for (String guess : guesses) {
            System.out.println("Guess: " + guess + " - Hint: " + puzzle.getHint(guess));
        }
    }
}

HiddenWord.main(null);
Guess: GHOSTS - Hint: G*****
Guess: THANKS - Hint: **++**
Guess: GAMBIT - Hint: GAM*+*
Guess: GAMBLE - Hint: GAM***
Guess: GAMING - Hint: GAMING

Notes