catDog string problem at Codingbat.com

While you are pretty close to a solution, there are a few critical problems in your code:

  1. Your call to substring() fetches a string of size 2. That string can never be cat nor dog. Change the second parameter in the method call to i + 3 to get 3 characters.
  2. Your call to substring() will throw an IndexOutOfRangeException, as i 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 your for loop to i < str.length() - 2.
  3. The return value of your method will always be true. In the case where dogAnswer != catAnswer you return exactly that expression – which will resolve to true. A possible solution: Merge the two return statements into return dogAnswer == catAnswer.

Additionally, there are a few things you could do to make your code simpler:

  1. There really is no need to copy cat_Count into catAnswer and dog_Count into dogAnswer. Throw away two of the variables, and use the other pair exclusively.
  2. If the input string is not allowed to contain anything else than cat and dog, your loop can be optimized to only consider every third position in the input string. Change i++ into i += 3. (Update: after seeing the test data used at CodingBat, I can tell that this is not the case.)

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

Leave a Comment