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; } }
If I used word.CharAt(i) instead of word.substring(i,i+1) would it still work?
You can use
charAt
to obtain a single character but you must properly handle the return value’s type.charAt
returns achar
rather than aString
.Is it OK if I put else if(word.indexOf(getLetter) == -1) at the end instead of just else
Sure. It’s an unnecessary check but it isn’t wrong.
If I used contains() instead of indexOf(), how many points will be taken off?
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.In getHint() is it ok in the for loop to do for(int i = 0; i < word.length()-1; i++)
Thanks
No, that would skip the last letter.
It could be
for(int i = 0; i <= word.length() – 1; i ++)
Sure, you could use symmetric loop bounds (
<= word.length() - 1
) instead of asymmetric bounds (< word.length()
).Can you use indexOf to do this problem. So for the for loop, i did this
if (word.indexOf(guessLetter) == i) {
hint += guessLetter;
}
No. indexOf finds the first occurrence. If there are multiple copies of the same letter, the second and subsequent ones would be mishandled.
Can you use the following code instead of looping through the whole entire String?
if(guess.equals(word)){
return guess;
}
Thank you!
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.
In the for loop instead of using word.length could you have used guess.length
Yes.
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?
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.