2017-02-17 89 views
1

我正在嘗試執行一個程序,該程序可以查找字符串中最大的連續出現次數。這是我的代碼。查找字符串中字符的最高連續出現次數拋出字符串索引超出範圍

public class Assign2{ 
    public int maxOcc(String str){ 
     System.out.println("Entered method"); 
     int j,i,counter; 
     j = i = 0; 
     int max = 0; 
     int size = str.length(); 
     System.out.println("Size of string-->"+size); 
     for(i = 0;i<size;i++){ 
      j = i; 
      counter = 0; 
      while(str.charAt(i)==str.charAt(j) && j < size){ 
       counter++; 
       j++; 
      } 
      if(counter > max) 
       max = counter; 
     } 
     return max; 
    } 
    public static void main(String args[]){ 
     Assign2 a = new Assign2(); 
     System.out.println(a.maxOcc("abbbbaaaaaagsgsgaaaa")); 
    } 
} 

但是,當我嘗試運行這個程序時,我產生了一個「字符串索引越界」。任何想法?

回答

1

的問題是在這種情況下:

while(str.charAt(i)==str.charAt(j) && j < size){ 

的Java評估左到右,所以它的計算結果str.charAt(j)它檢查j < size前 - 所以,如果j太大(因爲你在循環遞增)你會得到一個AIOOBE。

反轉的子表達式:一旦j < size是假的,它不打擾檢查它的其餘部分:

while (j < size && str.charAt(i)==str.charAt(j)){ 

因爲&&短路這不會失敗。

+0

哦,非常感謝你!!!!!!! –