KickJava   Java API By Example, From Geeks To Geeks.

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


1 package com.teamkonzept.lib.math;
2
3
4 public class CompareOperator extends BinaryOperator{
5     
6     final static int EQUAL = 0;
7     final static int NOT_EQUAL = 1;
8     final static int LESS = 2;
9     final static int LESS_OR_EQUAL = 3;
10     final static int GREATER = 4;
11     final static int GREATER_OR_EQUAL = 5;
12     
13     int type;
14
15     public CompareOperator(int type, int parenlevel, int position)
16     throws UnsupportedOperatorException{
17     super(parenlevel, getPriority(type, position), position);
18     this.type = type;
19     }
20     
21      /**
22      * evaluates that operator on that operands
23      * both must be of type Double
24      * result is of type Boolean
25      */

26     public Object JavaDoc evaluate(Object JavaDoc left, Object JavaDoc right)
27     throws BadOperandTypeException{
28     if ( !(left instanceof Double JavaDoc) )
29         throw new BadOperandTypeException(left, "Double");
30     if ( !(right instanceof Double JavaDoc) )
31         throw new BadOperandTypeException(right, "Double");
32     if ( type == EQUAL )
33         return new Boolean JavaDoc(((Double JavaDoc)left).doubleValue()
34                    == ((Double JavaDoc)right).doubleValue());
35     else if ( type == NOT_EQUAL )
36         return new Boolean JavaDoc(((Double JavaDoc)left).doubleValue()
37                    != ((Double JavaDoc)right).doubleValue());
38     else if ( type == LESS )
39         return new Boolean JavaDoc(((Double JavaDoc)left).doubleValue()
40                    < ((Double JavaDoc)right).doubleValue());
41     else if ( type == LESS_OR_EQUAL )
42         return new Boolean JavaDoc(((Double JavaDoc)left).doubleValue()
43                    <= ((Double JavaDoc)right).doubleValue());
44     else if ( type == GREATER )
45         return new Boolean JavaDoc(((Double JavaDoc)left).doubleValue()
46                    > ((Double JavaDoc)right).doubleValue());
47     else //if ( type == GREATER_OR_EQUAL )
48
return new Boolean JavaDoc(((Double JavaDoc)left).doubleValue()
49                    >= ((Double JavaDoc)right).doubleValue());
50     }
51
52
53     static int getPriority(int op, int position)
54     throws UnsupportedOperatorException{
55     switch ( op ){
56     case EQUAL:
57         return COMPARE_EQUAL_PRIORITY;
58     case NOT_EQUAL:
59         return COMPARE_EQUAL_PRIORITY;
60     case LESS:
61         return COMPARE_LESS_PRIORITY;
62     case LESS_OR_EQUAL:
63         return COMPARE_LESS_PRIORITY;
64     case GREATER:
65         return COMPARE_LESS_PRIORITY;
66     case GREATER_OR_EQUAL:
67         return COMPARE_LESS_PRIORITY;
68     default:
69         throw new UnsupportedOperatorException(CompareOperator.class,
70                            op, position);
71     }
72     }
73
74 }
75
Popular Tags