CS 46B - Lecture 9

Cover page image

Pre-class reading

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 multiplication can bind more strongly than addition.
  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

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:

Lecture 9 Clicker Question 3

Why does the expression parser use mutual recursion?

  1. To compute the value of an arithmetic expression more efficiently than with a loop
  2. To make * and / bind stronger than + and -
  3. To handle both operators such as * and / and numbers such as 2 and 3
  4. To handle parenthesized expressions, such as 2+3*(4+5)