[英]Java How to avoid String Index out of Bounds
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.
如果字符串“ cat”和“ dog”在给定的字符串中出现相同的次数,则返回true。
catDog("catdog") → true catDog("catcat") → false catDog("1cat1cadodog") → true
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
. 但是对于
catDog("catxdogxdogxca")
→ false
我得到了StringIndexOutOfBoundsException
。 I know it's caused by the if clause when it tries to check if the charAt(i+2)
equals t. 我知道它是由if子句在尝试检查
charAt(i+2)
等于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)
您正在使用
i < str.length()
作为循环终止条件,但是您正在使用str.charAt(i+1)
和str.charAt(i+2)
Since you need to access i+2
, then you should limit the range by i < str.length() - 2
instead. 由于您需要访问
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;
There is a problem with logic, the conditional statements are trying to access character which is out of string size. 逻辑存在问题,条件语句试图访问超出字符串大小的字符。
Input: catxdogxdogxca have ca at the end that's why else block is executed and which tries to get character present at i+3 which does not exist in the input. 输入: catxdogxdogxca在末尾有ca ,这就是为什么执行else块并试图获取i + 3处存在的字符(输入中不存在)的原因。 That's why you are seeing java.lang.StringIndexOutOfBoundsException .
这就是为什么您看到java.lang.StringIndexOutOfBoundsException的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.