【问题标题】:Index OutOfBound Exception for a piece of code?一段代码的索引 OutOfBound 异常?
【发布时间】:2025-11-21 18:50:01
【问题描述】:

我正在尝试运行下面的代码,但我得到了一个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");
    }
}

【问题讨论】:

  • 现在应该打印 "bcd" 这里 d 表示 'c' 之后的下一个字符
  • 这个方法的目的是什么,为什么要把abc硬编码为子字符串?
  • 现在缩进很好
  • 但我不明白,当你发现abc 为什么要打印bcd 时,前面是一个字符。如果你试图在你的字符串中找到abc 的所有外观,它不会给出。

标签: java string indexoutofboundsexception


【解决方案1】:

您应该在 while-loop 条件中使用此条件,

while (index < input.length()-3 && index >= 0) { }

【讨论】: