2017-02-17 65 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

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

相关问题