英文:
How to prevent an ArrayIndexOutOfBoundsException in this case?
问题
问题是:
给定一个字符串:aaaBBB
我需要打印出:a3B3
(计算给定字符串中每个字母的出现次数)。
我尝试了以下代码:
String x = "aaaBBB";
char[] c = x.toCharArray();
StringBuilder sb = new StringBuilder();
int count = 1;
System.out.println(c.length);
for (int i = 0; i < c.length; i++) {
if (c[i] == c[i+1]) {
count++;
} else {
sb.append(c[i]).append(count);
count = 1;
}
}
System.out.println(sb);
在我的最后一次迭代中,当我将c[i]与c[i+1]进行比较时,我遇到了ArrayIndexOutOfBounds异常(很明显,因为索引i+1不存在)。
我想知道一些避免出现这个异常的方法,而不改变if条件。
可能听起来研究不够充分,但我已经尝试了相当长的时间,但在发布到这里之前还没有找到解决方法。
英文:
The question is:
given a string: aaaBBB
I need to print: a3B3
(counting occurrences of each letter in a given string).
I tried the following:
String x = "aaaBBB";
char[] c = x.toCharArray();
StringBuilder sb = new StringBuilder();
int count = 1;
System.out.println(c.length);
for (int i = 0; i < c.length; i++) {
if (c[i] == c[i+1]) {
count++;
} else {
sb.append(c[i]).append(count);
count = 1;
}
}
System.out.println(sb);
I'm getting an ArrayIndexOutOfBounds Exception, for my last iteration, when I check c[i] with c[i+1] (pretty obvious, because the index i+1 doesn't exist).
I'd want to know some ways to avoid getting this exception, without changing the if condition.
Might sound like poor research, but I've been trying this for quite some time now, but not able to get through, before posting it here.
答案1
得分: 0
尝试以下内容:
- 将第一个字符分配给一个独立的变量。
- 当不再等于后续字符时,将该字符和计数添加到字符串中。
- 然后将该字符和计数重置为下一个字符和 1。
- 当所有字符都用完时,添加最后一个字符和计数。
String x = "aaaaBBBcDDDDD";
char[] c = x.toCharArray();
StringBuilder sb = new StringBuilder();
int count = 1;
char ch = c[0];
for (int i = 1; i < c.length; i++) {
if (c[i] == ch) {
count++;
} else {
sb.append(ch).append(count);
ch = c[i];
count = 1;
}
}
sb.append(ch).append(count);
System.out.println(sb);
输出结果
a4B3c1D5
英文:
Try the following:
- assign the first character to an independent variable.
- when no longer equal to subsequent characters. Add to the string with that character and count.
- then reset that character and count to the next one and 1.
- when all characters are exhausted, add the final character and count.
String x = "aaaaBBBcDDDDD";
char[] c = x.toCharArray();
StringBuilder sb = new StringBuilder();
int count = 1;
char ch = c[0];
for (int i = 1; i < c.length; i++) {
if (c[i] == ch) {
count++;
} else {
sb.append(ch).append(count);
ch = c[i];
count = 1;
}
}
sb.append(ch).append(count);
System.out.println(sb);
Prints
a4B3c1D5
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论