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));
}
}
substring) when calling recursivelycount.XX. Check if the character isx, if it is, chop it off for the next invocation. If it'sX, check the next one to see if it'sXX. If it is, add1; otherwise, return the value from the next invocation.