I am trying to get more familiar with recursion in java. I am trying to count number of times character occurs in a given string.
public class apptest {
public static void main(String[] args) {
apptest c = new apptest();
String input = "aaa";
char p = 'a';
c.freq(input, p);
}
public int freq(String c, char p) {
if (c.length() == 0) {
return 0;
} else if (c.charAt(0) == p) {
return 1 + freq(c.substring(1, c.length()), p);
} else
return freq(c.substring(1, c.length()), p);
}
}
I am not getting any output. and completely confused on how to solve a problem like this. I looked online and found the freq(c.substring(1, c.length()),p); part but going through the code it doesn't make sense.. seems like on every pass its still going to deal with 'aa' and not necessarily shrink it.. what am I not seeing?