我正在尝试计算一个字母在字符串 (aabcccccaaa
) 中出现的次数,并将它出现的次数与相应的字母一起放入新字符串中。问题是我得到一个 StringIndexOutOfBoundsException
。
我有点知道为什么,但我认为这主要是因为我的逻辑在这个问题上有缺陷。
我走在正确的轨道上吗?我做错了什么,我该如何解决?
例如,输出应该是a2b1c5a3
这是我的代码:
public class Problem {
public static void main(String []args) {
String str = "aabcccccaaa";
System.out.println(compressBad(str));
}
public static String compressBad(String str) {
int countConsecutive = 0;
String compressedString = "";
for(int i = 0; i < str.length(); i++) {
if(str.charAt(i) != str.charAt(i + 1)) {
countConsecutive++;
compressedString += "" + str.charAt(i) + countConsecutive;
countConsecutive = 0;
}
}
return compressedString;
}
}
最佳答案
当i
是最后一个索引时,str.charAt(i + 1)
这行会读出边界,i+1
是现在出界了。
关于java - 就得出解决方案而言,我的程序中的逻辑是否接近?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54576792/