KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > teamkonzept > lib > math > MathBinaryOperator


1 package com.teamkonzept.lib.math;
2
3 public class MathBinaryOperator extends BinaryOperator{
4     
5     final static int PLUS = 0;
6     final static int MINUS = 1;
7     final static int MULT = 2;
8     final static int DIV = 3;
9     final static int MODULO = 4;
10     final static int INT_DIV = 5;
11     final static int POW = 6;
12     int type;
13
14     public MathBinaryOperator(int type, int parenlevel, int position)
15     throws UnsupportedOperatorException{
16     super(parenlevel, getPriority(type, position), position);
17     this.type = type;
18     }
19
20     /**
21      * evaluates this operator to that operands
22      * returns the result of type Double
23      */

24     public Object JavaDoc evaluate(Object JavaDoc left, Object JavaDoc right)
25     throws BadOperandTypeException{
26     if ( !(left instanceof Double JavaDoc) )
27         throw new BadOperandTypeException(left, "Double");
28     if ( !(right instanceof Double JavaDoc) )
29         throw new BadOperandTypeException(right, "Double");
30     double d1 = ((Double JavaDoc)left).doubleValue();
31     double d2 = ((Double JavaDoc)right).doubleValue();
32     switch ( type ){
33     case PLUS:
34         return new Double JavaDoc(d1 + d2);
35     case MINUS:
36         return new Double JavaDoc(d1 - d2);
37     case MULT:
38         return new Double JavaDoc(d1 * d2);
39     case DIV:
40         return new Double JavaDoc(d1 / d2);
41     case MODULO:
42         double intdiv = Math.floor(d1 / d2);
43         return new Double JavaDoc(d1 - d2 * intdiv);
44     case INT_DIV:
45         return new Double JavaDoc(Math.floor(d1 / d2));
46     case POW:
47         return new Double JavaDoc(Math.pow(d1, d2));
48         default:
49             // cant happen
50
}
51     return null;
52     }
53
54
55     static int getPriority(int op, int position)
56     throws UnsupportedOperatorException{
57     switch ( op ){
58     case PLUS:
59         return MATH_ADD_PRIORITY;
60     case MINUS:
61         return MATH_ADD_PRIORITY;
62     case MULT:
63         return MATH_MULT_PRIORITY;
64     case DIV:
65         return MATH_MULT_PRIORITY;
66     case MODULO:
67         return MATH_MULT_PRIORITY;
68     case INT_DIV:
69         return MATH_MULT_PRIORITY;
70     case POW:
71         return MATH_EXP_PRIORITY;
72     default:
73         throw new UnsupportedOperatorException(MathBinaryOperator.class,
74                            op, position);
75     }
76     }
77 }
78
Popular Tags