HiddenWord free response answer 18

HiddenWord free response problem from the 2015 AP Computer Science A Exam.

HiddenWord is #2 from the from the 2015 AP Computer Science A Free Response problems.


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 < word.length(); i++)
      String guessLetter = guess.substring(i, i + 1);
      if(word.substring(i, i + 1).equals(guessLetter))
        hint += guessLetter;
      else if(word.indexOf(guessLetter) != -1)
        hint += "+";
        hint += "*";
    return hint;

18 thoughts on “HiddenWord free response answer

  1. Michael Kim May 10,2015 10:17 am

    If I used word.CharAt(i) instead of word.substring(i,i+1) would it still work?

    • Brandon Horn May 10,2015 11:25 am

      You can use charAt to obtain a single character but you must properly handle the return value’s type. charAt returns a char rather than a String.

  2. ct May 10,2015 11:01 am

    Is it OK if I put else if(word.indexOf(getLetter) == -1) at the end instead of just else

  3. David May 10,2015 11:31 am

    If I used contains() instead of indexOf(), how many points will be taken off?

    • Brandon Horn May 10,2015 10:15 pm

      contains, if used correctly, would work fine. I don’t have the scoring guide but typically any correct code receives full credit unless it rewrites an accessible method.

  4. Nobody May 10,2015 5:23 pm

    In getHint() is it ok in the for loop to do for(int i = 0; i < word.length()-1; i++)

  5. math rules Dec 8,2017 4:37 pm

    Can you use indexOf to do this problem. So for the for loop, i did this

    if (word.indexOf(guessLetter) == i) {
      hint += guessLetter;

    • Brandon Horn Dec 9,2017 8:24 am

      No. indexOf finds the first occurrence. If there are multiple copies of the same letter, the second and subsequent ones would be mishandled.

  6. Person Mar 21,2018 5:23 pm

    Can you use the following code instead of looping through the whole entire String?

    return guess;

    Thank you!

    • Brandon Horn Mar 25,2018 9:57 pm

      You could add that to the top of your method if you’d like. You still have to do everything else that’s already shown to generate a hint for any guess that doesn’t match the entire word.

  7. Random Mar 27,2018 9:37 am

    In the for loop instead of using word.length could you have used guess.length

  8. Ksoares Feb 4,2019 4:32 pm

    I am new to Java, and do not understand the use of -1 in the line: else if(word.indexOf(guessLetter) != -1)
    Could you explain?

    • Brandon Horn Feb 5,2019 6:36 pm

      The indexOf method returns -1 if the argument is not found in the implicit parameter. The line is checking if guessLetter is not in word.

Comments are closed.