Advertisement
Ladies_Man

Expr. Visitor for calculations

Nov 10th, 2014
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.83 KB | None | 0 0
  1. public class EvalVisitor implements ExprVisitor<Integer>{
  2.         private int res;
  3.     private int x1;
  4.     public EvalVisitor(int x) {
  5.         this.x1 = x;
  6.     }
  7.    
  8.     public int eval (Expr<Integer> e) {
  9.         e.accept(this);         //recognize subexpression
  10.         return res;         //update result of it on level above
  11.     }
  12.        
  13.     public void visitNeg(Neg<Integer> e) {
  14.         res = -eval(e.a());
  15.     }
  16.        
  17.     public void visitBinary(Binary<Integer> e) {
  18.         if (e.operation() == '+') {
  19.             res = eval(e.a()) + eval(e.b());    //dig into operand
  20.         } else if (e.operation() == '-') {          //to check if its subexpr
  21.                    res = eval(e.a()) - eval(e.b());
  22.                } else if (e.operation() == '*') {
  23.                           res = eval(e.a()) * eval(e.b());
  24.                       } else if (e.operation() == '/') {
  25.                                  res = eval(e.a()) / eval(e.b());
  26.                              }
  27.     }
  28.        
  29.     public void visitVar(Var<Integer> e) {
  30.         res = x1;   //cant dig deeper => get and return variable
  31.     }
  32.        
  33.     public void visitConst(Const<Integer> e) {
  34.         res = e.value();    // -||- => get and ret constant
  35.     }
  36. }
  37.  
  38. //========================================================================================
  39.  
  40. public class Test
  41. {
  42.         public static void main(String[] args)
  43.         {
  44.                 ExprFactory<Integer> f = new ExprFactory<Integer>();
  45.  
  46.                 Expr<Integer> e =
  47.                         f.newBinary(
  48.                                 f.newBinary(
  49.                                         f.newVar(),
  50.                                         f.newConst(10),
  51.                                         ’+
  52.                                 ),
  53.                                 f.newVar(),
  54.                                 ’*
  55.                         );
  56.  
  57.                 EvalVisitor v = new EvalVisitor(5);
  58.                 System.out.println(v.eval(e));
  59.         }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement