-1
我想运行下面的代码,但我得到一个IndexOutOfBoundsException
。我知道问题出在哪里,但为了改进代码,我想添加一条if
语句,如果索引超出范围,则while
循环会中断。它现在应该打印"bcd"
而不会引发异常。索引OutOfBound异常的一段代码?
相信if语句应该用于这个:index > input.length() - 3
但我在哪里添加它?
public class test {
public void findAbc(String input) {
int index = input.indexOf("abc");
while (true) {
if (index == -1) {
break;
}
String found = input.substring(index + 1, index + 4);
System.out.println(found);
index = input.indexOf("abc", index + 4);
}
}
public void test() {
findAbc("abcdabc");
}
}
**现在应打印“BCD” **这里d指“C” –
后,下一个字符是什么这样做的目的方法,以及为什么你要将'abc'作为子字符串硬编码? –
现在很好地缩进了 –