gpt4 book ai didi

java - 查找字符串中字符的最高连续出现次数会导致字符串索引超出范围

转载 作者:行者123 更新时间:2023-11-30 06:53:20 26 4
gpt4 key购买 nike

我正在尝试编写一个程序来查找字符串中最大的连续出现次数。这是我的代码。

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"));
}
}

但是,当我尝试运行这个程序时,我生成了一个“字符串索引超出范围”。有什么想法吗?

最佳答案

问题是在这种情况下:

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

Java 从左到右计算,因此它计算 str.charAt(j)在检查之前 j < size - 所以如果 j太大(因为你在循环中递增),你将得到一个 AIOOBE。

反转子表达式:

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

这不会失败,因为 &&短路:一次j < size是假的,它不会费心检查其余部分。

关于java - 查找字符串中字符的最高连续出现次数会导致字符串索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42307545/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com