View Javadoc
1 /*** 2 * ArithmeticOperator.java 3 * 4 * $Author: mballesteros $ 5 * $Date: 2003/11/28 19:18:03 $ 6 * $Revision: 1.1 $ 7 */ 8 package net.sf.jec; 9 10 /*** 11 * 12 * @author mballesteros 13 */ 14 public class ArithmeticOperator extends Operator { 15 16 private static final int ADD = 0; 17 private static final int SUBSTRACT = 1; 18 private static final int MULTIPLY = 2; 19 private static final int DIVIDE = 3; 20 private static final int MOD = 4; 21 22 private int type; 23 private Operator op1, op2; 24 private boolean throwExceptions; 25 26 /*** Creates a new instance of BooleanOperator */ 27 public ArithmeticOperator(String type, Operator op1, Operator op2, boolean throwExceptions) { 28 if (type.equals("+")) this.type = ADD; 29 else if (type.equals("-")) this.type = SUBSTRACT; 30 else if (type.equals("*")) this.type = MULTIPLY; 31 else if (type.equals("/")) this.type = DIVIDE; 32 else if (type.equals("%")) this.type = MOD; 33 this.op1 = op1; 34 this.op2 = op2; 35 this.throwExceptions = throwExceptions; 36 } 37 38 /*** Returns a function representation String for this operator 39 */ 40 public String toFunctionString() { 41 return "Arithmetic(" + (type==ADD?"+":(type==SUBSTRACT?"-":(type==MULTIPLY?"*":(type==DIVIDE?"/":"%")))) 42 + ", " + op1 + ", " + op2 + ")"; 43 } 44 45 /*** Returns an expression String representation for this operator 46 */ 47 public String toExpressionString() { 48 return "(" + op1 + (type==ADD?"+":(type==SUBSTRACT?"-":(type==MULTIPLY?"*":(type==DIVIDE?"/":"%")))) 49 + op2 + ")"; 50 } 51 52 53 54 /*** Returns the associated value to the given context and root context 55 * @param rootCtx The root context, needed for operators that require 56 * expression evaluation from root point. Example: Indexer operators 57 * @param ctx The current context where the operator will work over 58 */ 59 protected Object directMap(Object rootCtx, Object ctx) throws EvaluationException { 60 try { 61 double d1 = ObjectConverter.toDouble(op1.apply(rootCtx, ctx)); 62 double d2 = ObjectConverter.toDouble(op2.apply(rootCtx, ctx)); 63 64 switch (type) { 65 case ADD: return new Double(d1+d2); 66 case SUBSTRACT: return new Double(d1-d2); 67 case MULTIPLY: return new Double(d1*d2); 68 case DIVIDE: return new Double(d1/d2); 69 case MOD: return new Integer( ((int)d1)%((int)d2)); 70 default: 71 return null; 72 } 73 } catch (ConversionException ce) { 74 return op1.apply(rootCtx, ctx).toString() 75 + op2.apply(rootCtx, ctx).toString(); 76 } 77 } 78 }

This page was automatically generated by Maven