我有以下任务要做:
如果字符串"cat“和”狗“在给定字符串中出现的次数相同,则返回true。 catDog("catdog")→true catDog("catcat")→false catDog(“1 cat1cado分析法”)→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时,我如何避免这种情况?(谢谢:)
发布于 2018-08-29 09:14:48
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)和str.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-29 09:24:29
逻辑有一个问题,条件语句试图访问字符串大小之外的字符。
输入:catxdogxdogxca的末尾有ca,这就是执行块的原因,它试图在输入中不存在的i+3中获取字符。所以你才会看到java.lang.StringIndexOutOfBoundsException.
https://stackoverflow.com/questions/52073708
复制相似问题