Only Collects First Index in java

Ex: The test case getCharsThatFollowPattern("abcabdabcab", "ab") should return the ArrayList ['c', 'd', 'c'].

I'm having problems trying to get the list to iterate through the pattern text. I get ['a', 'a', 'a'] in my test case instead of ['c', 'd', 'c'].

The code below finds where the next pattern starts – indexOfNextPatternStart – that would be where ever "ab" occurs next. Then it adds the length of "ab" itself to get whatever index is after that. So in your text example, it starts with "abc" – "ab" is clearly at the front, but you want the index of "c". That's what indexOfCharAfterPattern contains. At that point, you've got the character isolated. In my example, I'm storing that temporarily as charAfterPattern and printing it out.

I added the if (indexOfCharAfterPattern < text.length()) check to protect against the last "ab" in text. There's nothing after that last "ab", so trying to look ahead for the next character won't work.

public static void printThatFollowPattern(String text, String pattern) {
    int i = 0;
    while (i < text.length()) {
        int indexOfNextPatternStart = text.indexOf(pattern, i);
        int indexOfCharAfterPattern = indexOfNextPatternStart + pattern.length();

        if (indexOfCharAfterPattern < text.length()) {
            char charAfterPattern = text.charAt(indexOfCharAfterPattern);
            System.out.println("charAfterPattern: " + charAfterPattern);
        } else {
            break;
        }

        i = indexOfCharAfterPattern + 1;
    }
}