next up previous
Next: Computing values using recursion Up: Unit 11 Previous: Counting elements using recursion

Conditional counting of elements using recursion

We want to count only those elements of a file that satisfy a given condition. A recursive method to do so has the following structure:

read an element;
if (element is not valid)
  return 0;
else if (condition)
  return 1 + result-of-the-recursive-call;
else
  return result-of-the-recursive-call;

Example: Counting the number of lines of a file that start with ':'

public static int countLinesColon(BufferedReader br) throws IOException {
  String s = br.readLine();
  if (s == null)
    return 0;
  else if (s.charAt(0) == ':')
    return 1 + countLinesColon(br);
  else
    return countLinesColon(br);
}


next up previous
Next: Computing values using recursion Up: Unit 11 Previous: Counting elements using recursion