2014-10-05 59 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