【发布时间】:2019-11-14 22:21:38
【问题描述】:
我正在制作一种方法,它采用指定的字符串并计算每个连续字母出现的次数。
例如:
编码(“aabbcc”);
应该给出输出 2 2 2,因为有 2 个字母按顺序出现
我的代码是:
for(int i=0;i<word.length()-1;i++) {
int count=1;
if(i!=word.length()-1) {
//System.out.println(word.charAt(i));
//System.out.println(word.charAt(i+1));
try {
while(word.charAt(i)==word.charAt(i+1)) {
count++;
i++;
}
} catch (Exception e) {}
System.out.print(count+" ");
}
}
但它一直给我一个IndexOutOfBoundsException,所以我只是添加了一个 try and catch 块,但我知道有更好的方法
【问题讨论】:
-
这条线
catch (Exception e) {}通常不是一件好事。我会删除该 try catch 并使用适当的应用程序流程修复任何异常。
标签: java string algorithm count