Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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++;
        }
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading