Evaluator.java.html

  1  /**
  2     A class that can compute the value of an arithmetic expression.
  3  */
  4  public class Evaluator
  5  {
  6     private ExpressionTokenizer tokenizer;
  7  
  8     /**
  9        Constructs an evaluator.
 10        @param anExpression a string containing the expression
 11        to be evaluated
 12     */
 13     public Evaluator(String anExpression)
 14     {
 15        tokenizer = new ExpressionTokenizer(anExpression);
 16     }
 17  
 18     /**
 19        Evaluates the expression.
 20        @return the value of the expression.
 21     */
 22     public int getExpressionValue()
 23     {
 24        int value = getTermValue();
 25        boolean done = false;
 26        while (!done)
 27        {
 28           String next = tokenizer.peekToken();
 29           if ("+".equals(next) || "-".equals(next))
 30           {
 31              tokenizer.nextToken(); // Discard "+" or "-"
 32              int value2 = getTermValue();
 33              if ("+".equals(next)) { value = value + value2; }
 34              else { value = value - value2; }
 35           }
 36           else 
 37           {
 38              done = true;
 39           }
 40        }
 41        return value;
 42     }
 43  
 44     /**
 45        Evaluates the next term found in the expression.
 46        @return the value of the term
 47     */
 48     public int getTermValue()
 49     {
 50        int value = getFactorValue();
 51        boolean done = false;
 52        while (!done)
 53        {
 54           String next = tokenizer.peekToken();
 55           if ("*".equals(next) || "/".equals(next))
 56           {
 57              tokenizer.nextToken();
 58              int value2 = getFactorValue();
 59              if ("*".equals(next)) { value = value * value2; }
 60              else { value = value / value2; }
 61           }
 62           else 
 63           {
 64              done = true;
 65           }
 66        }
 67        return value;
 68     }
 69  
 70     /**
 71        Evaluates the next factor found in the expression.
 72        @return the value of the factor
 73     */
 74     public int getFactorValue()
 75     {
 76        int value;
 77        String next = tokenizer.peekToken();
 78        if ("(".equals(next))
 79        {
 80           tokenizer.nextToken(); // Discard "("
 81           value = getExpressionValue();
 82           tokenizer.nextToken(); // Discard ")"
 83        }
 84        else
 85        {
 86           value = Integer.parseInt(tokenizer.nextToken());
 87        }
 88        return value;
 89     }
 90  }