Search code examples
javarecursionstringindexoutofbounds

Java recursion Index out of range 1


I am currently trying to figure out why the cases that end with x results in an OutOfBoundsError like the 3 test cases below.

The assignment is to count the number of 'x' in a string; if an 'x' is follow by another 'x' counted as double.

Thank you, and I would very grateful if you can help.

public class CountXWithDubs {

    /**
     * Count the number of 'x's in the string. Any 'x' that is followed by
     * another 'x' should count double (e.g. "axxbxc" -> 4)
     * 
     * @param x a string.
     * @return the count of x's.
     */
    public static int countXWithDubs(String s) {
        if(s == null || s.isEmpty()) {
            return 0;
        }
        int count = 0;
        if(s.charAt(0) == 'x') {
            if(s.charAt(1) == 'x') {
                count += 2;
            }
            else {
                count++;
            }
        }
        return count + countXWithDubs(s.substring(1));
    }

    @Test
    public void testXSEnd() {
        assertEquals("Incorrect result with x at end", 2,
                countXWithDubs("abxcdx"));
    }
    
    @Test
    public void testDoubleXEnd() {
        assertEquals("Incorrect result with double x at end", 4,
                countXWithDubs("abxcdxx"));
    }
    
    @Test
    public void testBunchOfXs() {
        assertEquals("Incorrect result with bunch of x's", 13,
                countXWithDubs("xxxaxbxxcxdxx"));
    }
}

Solution

  • OutOfBoundsError will occur if the length of string s is 1,then s.charAt(1) will cause this error,so you need to check the length when you visit the next element

        if(s.charAt(0) == 'x') {
            if(s.length()>1 &&s.charAt(1) == 'x') {
                count += 2;
            }else {
                count++;
            }
        }