I have the following task to do:
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
my code:
public boolean catDog(String str) {
int catC = 0;
int dogC = 0;
if(str.length() < 3) return true;
for(int i = 0; i < str.length(); i++){
if(str.charAt(i) == 'd' && str.charAt(i+1) == 'o' && str.charAt(i+2) == 'g'){
dogC++;
}else if(str.charAt(i) == 'c' && str.charAt(i+1) == 'a' &&
str.charAt(i+2) == 't'){
catC++;
}
}
if(catC == dogC) return true;
return false;
}
But for catDog("catxdogxdogxca")
→ false
I'm getting a StringIndexOutOfBoundsException
. I know it's caused by the if clause when it tries to check if the charAt(i+2)
equals t. How can I avoid this?
Thanks in regards :)
for(int i = 0; i < str.length(); i++){ // you problem lies here
if(str.charAt(i) == 'd' && str.charAt(i+1) == 'o' && str.charAt(i+2) == 'g')
You are using the i < str.length()
as the loop termination condition but you are using str.charAt(i+1)
and str.charAt(i+2)
Since you need to access i+2
, then you should limit the range by i < str.length() - 2
instead.
for(int i = 0, len = str.length - 2; i < len; i++)
// avoid calculating each time by using len in initialising phase;