2014-10-05 54 views
-1

代码应该这样做:返回给定字符串中任何位置出现字符串“code”的次数,除非我们接受任何字母作为'd',所以“应付”和“cooe”数。太多例外越界 - JAVA

问题:java.lang.StringIndexOutOfBoundsException:跨异常冉字符串索引超出范围:11(行号:10)

public int countCode(String str){ 
int a = 0; // counter goes thru string 
int b = str.length()-1; 
int counter = 0; //counts code; 
if(str.length() < 4) return 0; 
else{ 
while (a <=b){ 
if(str.charAt(a) == 'c'){ 
    if(str.charAt(a+1) == 'o'){ 
if(str.charAt(a+3) == 'e'){ 
    counter++; 
    a= a+3; 
} // checks e 
    else a++; 
    } // checks o 
    else a++; 
} // checks c 
else a++; 
} 

return counter; 
} 
} 

这里就是我试图评估以得到所述例外:

  • countCode( “xxcozeyycop”) - >预期的结果
  • countCode( “cozcop”) - >预期的结果

+0

见[此篇](http://stackoverflow.com/questions/2635082/java-counting-of-occurrences-of-a-word-in-a-string) – Benvorth 2014-10-05 13:51:40

回答

0

你的循环从0到该字符串的长度(排除)。但内循环,你正在做

str.charAt(a+3) 

显然,如果alength - 1a + 3length + 2,因此你想字符串的范围之外访问的元素。

附注:如果你正确地缩进它,你会更好地理解你自己的代码。

0

而不是

while (a <=b){ 

使用

while (a <= b - 3){ 

原因:在同时您的最终标志是条件的String"code"开始是String内。但是,如果a = b-2,则a + 3 = b + 1 =(str.length() - 1 + 1)= str.length(),它恰好在String之外。

0
public int countCode(String str) { 
    int count = 0; 
    for(int i = 0; i < str.length()-3; i++) 
    if(str.substring(i, i+2).equals("co") && str.charAt(i+3) == 'e') 
     count++; 

    return count; 
} 
+2

欢迎SO。请不要,该代码只回答不符合SO的标准。请参阅http://stackoverflow.com/help/how-to-answer – 2017-01-28 15:51:00

+2

请在答案中添加一些解释。 – 2017-01-28 18:36:33