我正在尝试运行下面的代码,但得到了IndexOutOfBoundsException
。我知道问题出在哪里,但是为了改进代码,我想添加一条if
语句,以便while
在索引超出范围时中断循环。现在,它应该打印"bcd"
而不会引发异常。
相信应该为此使用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");
}
}
您应该在自己的while-loop
情况下使用此条件,
while (index < input.length()-3 && index >= 0) { }
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句