0

我有以下任务要做:

如果字符串“cat”和“dog”在给定字符串中出现的次数相同,则返回 true。

catDog("catdog") → true catDog("catcat") → false catDog("1cat1cadodog") → true

我的代码:

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;
}

但是对于catDog("catxdogxdogxca")false我得到一个StringIndexOutOfBoundsException. 我知道这是由 if 子句尝试检查是否charAt(i+2)等于 t 引起的。我怎样才能避免这种情况?致谢:)

4

2 回答 2

2
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')

您正在使用i < str.length()作为循环终止条件,但您正在使用str.charAt(i+1)andstr.charAt(i+2)

既然您需要访问i+2,那么您应该改为限制范围i < str.length() - 2

for(int i = 0, len = str.length - 2; i < len; i++) 
// avoid calculating each time by using len in initialising phase;
于 2018-08-29T09:14:48.170 回答
0

逻辑有问题,条件语句试图访问超出字符串大小的字符。

输入:catxdogxdogxca 末尾ca这就是执行else块的原因,它试图获取输入中不存在的 i+3 处的字符。这就是您看到java.lang.StringIndexOutOfBoundsException的原因。

于 2018-08-29T09:24:29.843 回答