While you are pretty close to a solution, there are a few critical problems in your code:
- Your call to
substring()
fetches a string of size2
. That string can never becat
nordog
. Change the second parameter in the method call toi + 3
to get3
characters. - Your call to
substring()
will throw anIndexOutOfRangeException
, asi
approaches the end of the length of the input string. Make sure you do not ask for a substring that “overflows” the length of the input string. One way to fix this bug, would be to change the conditional expression in yourfor
loop toi < str.length() - 2
. - The return value of your method will always be
true
. In the case wheredogAnswer != catAnswer
you return exactly that expression – which will resolve totrue
. A possible solution: Merge the tworeturn
statements intoreturn dogAnswer == catAnswer
.
Additionally, there are a few things you could do to make your code simpler:
- There really is no need to copy
cat_Count
intocatAnswer
anddog_Count
intodogAnswer
. Throw away two of the variables, and use the other pair exclusively. If the input string is not allowed to contain anything else than(Update: after seeing the test data used at CodingBat, I can tell that this is not the case.)cat
anddog
, your loop can be optimized to only consider every third position in the input string. Changei++
intoi += 3
.
After implementing fix #1, #2 and #3 as well as suggestion #1, I have made a test run using the provided test bench, and the result is quite satisfying:
All correct