0

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

2 Answers 2

1

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++;
        }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

thank you! I tried that but apparently I put the check length condition after like this (s.charAt(1) == 'x' && s.length()>1) so it didn't work lol. Thank you again!
0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.