Advertisement
Guest User

Untitled

a guest
May 4th, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.64 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.Map;
  4.  
  5. public abstract class BinaryExpression extends BaseExpression {
  6.     protected Expression exp1;
  7.     protected Expression exp2;
  8.    
  9.     public BinaryExpression(Expression exp1, Expression exp2) {
  10.         this.exp1 = exp1;
  11.         this.exp2 = exp2;
  12.     }
  13.    
  14.     public String toString() {
  15.         return makeExpression(this.getPrefix(), this.exp1.toString(), this.exp2.toString(), this.getOperator());
  16.     }
  17.  
  18.     public Expression assign(String var, Expression expression) {
  19.         Expression returnExp1 = this.exp1;
  20.         Expression returnExp2 = this.exp2;
  21.         if (this.exp1.getVariables().contains(var)) {
  22.             returnExp1 = expression.assign(var, expression);
  23.         }
  24.        
  25.         if (this.exp2.getVariables().contains(var)) {
  26.             returnExp2 = expression.assign(var, expression);
  27.         }
  28.         return this.newExpressionInstance(returnExp1, returnExp2);     
  29.     }
  30.    
  31.     public List<String> getVariables() {
  32.         List<String> returnArray = new ArrayList<String>();
  33.         List<String> exp2List = exp2.getVariables();
  34.  
  35.         returnArray.addAll(exp1.getVariables());
  36.         returnArray.removeAll(exp2List);
  37.         returnArray.addAll(exp2List);
  38.         return returnArray;
  39.     }
  40.    
  41.     public double evaluate(Map<String, Double> assignment) throws Exception {
  42.         return this.doOperation(this.exp1.evaluate(assignment), this.exp2.evaluate(assignment));
  43.     }
  44.    
  45.     public double evaluate() throws Exception {
  46.         return this.doOperation(this.exp1.evaluate(), this.exp2.evaluate());
  47.     }
  48.    
  49.     protected abstract double doOperation(double num1, double num2);
  50.    
  51.     protected abstract Expression newExpressionInstance(Expression exp1, Expression exp2);
  52.    
  53.     protected abstract String getOperator();
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement