Mutual Recursion

13.5

Mutual Recursions

Syntax Diagrams for Evaluating an Expression

Mutual Recursions

Syntax Tree for Two Expressions

Mutually Recursive Methods

Lecture 9 Clicker Question 1

Why do we need both terms and factors?

  1. Factors are combined by multiplicative operators (* and /), terms are combined by additive operators (+, -).
  2. Terms are combined by multiplicative operators (* and /), factors are combined by additive operators (+, -).
  3. We need both so that addition can bind more strongly than multiplication.
  4. We need both so that we can have mutual recursion

The getExpressionValue Method

public int getExpressionValue()
{
   int value = getTermValue(); 
   boolean done = false; 
   while (!done) 
   { 
      String next = tokenizer.peekToken(); 
      if ("+".equals(next) || "-".equals(next)) 
      { 
         tokenizer.nextToken(); // Discard "+" or "-" 
         int value2 = getTermValue(); 
         if ("+".equals(next)) value = value + value2; 
         else value = value - value2; 
      } 
      else 
      { 
         done = true; 
      } 
   } 
   return value; 
}

The getTermValue Method

The getTermValue method calls getFactorValue in the same way, multiplying or dividing the factor values

public int getTermValue()
   {
      int value = getFactorValue();
      boolean done = false;
      while (!done)
      {
         String next = tokenizer.peekToken();
         if ("*".equals(next) || "/".equals(next))
         {
            tokenizer.nextToken();
            int value2 = getFactorValue();
            if ("*".equals(next)) { value = value * value2; }
            else { value = value / value2; }
         }
         else 
         {
            done = true;
         }
      }
      return value;
   }

The getFactorValue Method

public int getFactorValue() 
{ 
   int value; 
   String next = tokenizer.peekToken(); 
   if ("(".equals(next)) 
   { 
      tokenizer.nextToken(); // Discard "(" 
      value = getExpressionValue(); 
      tokenizer.nextToken(); // Discard ")" 
   } 
   else 
   { 
      value = Integer.parseInt(tokenizer.nextToken()); 
   } 
   return value; 
}

Lecture 9 Clicker Question 2

What happens if you try to parse the illegal expression 3+4*)5? Specifically, which method throws an exception?

  1. getExpressionValue
  2. getTermValue
  3. getFactorValue
  4. main

Using Mutual Recursions

To see the mutual recursion clearly, trace through the expression (3+4)*5:

Java heading

More about Java.