Search code examples
javastringindexoutofboundsexception

Index OutOfBound Exception for a piece of code?


I am trying to run the code below but I'm getting an IndexOutOfBoundsException. I know where the problem is but in order to improve the code, I want to add an if statement, such that the while loop breaks if the index is out of bounds. It should now print "bcd" without throwing an exception.

Believe that an if statement should be used for this: index > input.length() - 3 but where do I add it?

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");
    }
}

Solution

  • You should use this condition in your while-loop condition,

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