I'm having a bit of trouble trying to create a recursive method that counts the number of periods and spaces in a string. I can do this pretty easily using iteration, but I'm still fairly new to the concept of recursion. Here's my code so far, could anyone tell me where I'm going wrong?
public static int periodsAndSpaces(String s){ //option 3
if(s.length()<0){ //base case
return 0;
}
else if(s.charAt(0) == ' ' || s.charAt(0) == '.'){ //general case
return periodsAndSpaces(s.substring(1)) 1;
}
return 0;
}
CodePudding user response:
package com.test.demo;
public class Counter {
public static void main(String[] args) {
System.out.println(new Counter().countPeriodsAndSpaces(" test. . .a"));
}
int countPeriodsAndSpaces(String rs) {
if (rs == null || rs.isEmpty())
return 0;
char c = rs.charAt(0);
if (c == ' ' || c == '.')
return 1 countPeriodsAndSpaces(rs.substring(1));
else
return countPeriodsAndSpaces(rs.substring(1));
}
}
// Output 6
CodePudding user response:
New method with everyone's suggestions:
public static int periodsAndSpaces(String s){ //option 3
if(s.length()==0){ //base case
return 0;
}
else if(s.charAt(0) == ' ' || s.charAt(0) == '.'){
return periodsAndSpaces(s.substring(1)) 1;
}
else{
return periodsAndSpaces(s.substring(1));
}
}
Method stops running when there are no more characters left in the string, and I've added another case for adding onto the sum of periods and spaces when the current char doesn't have either of these.