HiddenWord free response answer 10

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.

https://secure-media.collegeboard.org/digitalServices/pdf/ap/ap15_frq_computer_science_a.pdf

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 += "+";
      else
        hint += "*";
    }
    
    return hint;
  }
}

10 thoughts on “HiddenWord free response answer

  1. Reply 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?

    • Reply 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. Reply 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. Reply David May 10,2015 11:31 am

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

    • Reply 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. Reply 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++)
    Thanks

Leave a Reply