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 becatnordog. Change the second parameter in the method call toi + 3to get3characters. - Your call to
substring()will throw anIndexOutOfRangeException, asiapproaches 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 yourforloop toi < str.length() - 2. - The return value of your method will always be
true. In the case wheredogAnswer != catAnsweryou return exactly that expression – which will resolve totrue. A possible solution: Merge the tworeturnstatements 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_CountintocatAnsweranddog_CountintodogAnswer. 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.)catanddog, 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