0

I am supposed to recursively count how many "XX" are in a string, if there is a small x in front of a double X it should not be counted. I am not sure what I am doing wrong; I seem to be getting stuck at the very first return, I keep getting 0.

UPDATE: I have everything working it seems, but XXxXXX keeps getting counted as 1 instead of 2.

    public static int count(String s) {

        if ((s.length() < 2))
            return 0;
        int counter = 0;
        if (s.charAt(0)== 'x')
        {
        if (s.substring(0, 2).equals("xX"))
            return count(s.substring(3));

        }
        if (s.substring(0, 2).equals("XX")) {
            return 1 + count(s.substring(3));
        }
        else
            return counter + count(s.substring(1));
        }



public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner kb = new Scanner(System.in);
    System.out.println("Enter a String: ");
    String s = kb.nextLine();
    System.out.println( count(s));
}

}

3
  • same homework? stackoverflow.com/q/39758831/2710704 Commented Sep 29, 2016 at 0:22
  • What should be the return if the string is "XXX" (1 or 2)? In other word, do you have to count overlapping "XX"? If so, decrease the position index (argument of substring) when calling recursively count. Commented Sep 29, 2016 at 2:15
  • Don't go by two unless you see XX. Check if the character is x, if it is, chop it off for the next invocation. If it's X, check the next one to see if it's XX. If it is, add 1; otherwise, return the value from the next invocation. Commented Sep 29, 2016 at 2:50

1 Answer 1

1

Since the end index in the call of substring is exclusive, the call of substring(0, 1) will never return a two-character string; only a string consisting of the first character will be returned.

To take two characters first check that the length is two or more, and then call substring(0, 2).

Sign up to request clarification or add additional context in comments.

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.