Logo

Collegeboard 2015 FRQ 2

Type: Method and Control Structures

Question 2

public class HiddenWord {
    private String word;

    public HiddenWord(String word) {
        this.word = word;
    }

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

        for (int i = 0; i < guess.length(); i++) {
            if (guess.charAt(i) == word.charAt(i)) {
                hint += guess.charAt(i);
            }
            else if (word.indexOf(guess.charAt(i)) != -1){
                hint += "+";
            }
            else{
                hint += "*";
            }
            // Add your other conditions if needed
        }

        return hint;
    }

    // Testing method
    public static void main(String[] args) {
        HiddenWord puzzle = new HiddenWord("HARPS");
        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);

H****
H*++*
HAR*S
HARPS

How indexOf to find character

  1. The indexOf method starts searching the string from the beginning (index 0).

  1. It examines each character in the string one by one.

  1. If the specified character (ch) is found, it returns the index of that character.

  1. If the character is not found, it returns -1.