Return true if the string "cat" and "dog" appear the same number of times in the given string.
catDog("catdog") → true
catDog("catcat") → false
catDog("1cat1cadodog") → true
public boolean catDog(String str) {
int countCat=0;
int countDog=0;
for(int i=0;i<str.length()-3;i++){
if(str.substring(i).startsWith("cat")){
countCat++;
}
if(str.substring(i).startsWith("dog")){
countDog++;
}
}
if(countCat==countDog){
return true;
}
else{
return false;
}
}
I am having trouble writing this method. Does anybody know why my code doesn't work correctly? Edit: The code compiles, however it gives the wrong output. For example if i put in "catdog" it returns false.