Home > Mobile >  Java recursion Index out of range 1
Java recursion Index out of range 1

Time:09-12

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

CodePudding user response:

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

CodePudding user response:

public static int countX(String str){
    if(str == null || str.isEmpty()) {
        return 0;
    }
    int currentPos = 0;
    int len = str.length();
    int count =  0;
    if(str.charAt(currentPos) == 'x'){
        if(currentPos 1 < len && str.charAt(currentPos 1)=='x'){
            count =2;
        }
        else{
            count =1;
        }
        
    }
    return count countX(str.substring(1));
}

Try this code, the problem would have occurred as charAt(1) in the last iteration when we have only one char. Adding another if condition will fix this

  • Related