Could anyone check my solution?
I want to return true if the string "cat" and "dog" appear the same number of times in the given string. There are various strings with different numbers of "cat" and "dog".
public boolean catDog(String str)
{
int catAnswer = 0;
int dogAnswer = 0;
int cat_Count = 0;
int dog_Count = 0;
for (int i=0; i< str.length()-1; i++)
{
String sub = str.substring(i, i+2);
if ((sub.equals("cat"))) cat_Count++;
if ((sub.equals("dog"))) dog_Count++;
catAnswer = cat_Count;
dogAnswer = dog_Count;
} //end for
if(dogAnswer == catAnswer ) {return true;}
// else
return (dogAnswer != catAnswer);
}
UPDATE:
If i use i + 3 i get an error code Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 7 (line number:10) - hence i use i + 2 (no errors are reported with it
Changing to i < str.length() - 4 gives a blanket response of true despite some of the test strings containing an unequal number of "cat" & "dog " tokens
The crux of the problem is that the response is either all true or all false when there is variable numbers of "cat" & "dog" in the various strings
the output from the code can be seen at http://codingbat.com/prob/p111624 - catDog string problem
Please try in cutting and pasting my code to see the output - this will explain more graphically than i could say