KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > nfunk > jep > function > Subtract


1 /*****************************************************************************
2
3 JEP - Java Math Expression Parser 2.3.0
4       October 3 2004
5       (c) Copyright 2004, Nathan Funk and Richard Morris
6       See LICENSE.txt for license information.
7
8 *****************************************************************************/

9 package org.nfunk.jep.function;
10
11 import java.util.*;
12 import org.nfunk.jep.*;
13 import org.nfunk.jep.type.*;
14
15 public class Subtract extends PostfixMathCommand
16 {
17     public Subtract()
18     {
19         numberOfParameters = 2;
20     }
21     
22     public void run(Stack inStack)
23         throws ParseException
24     {
25         checkStack(inStack); // check the stack
26

27         Object JavaDoc param2 = inStack.pop();
28         Object JavaDoc param1 = inStack.pop();
29         
30         inStack.push(sub(param1, param2));
31
32         return;
33     }
34     
35     public Object JavaDoc sub(Object JavaDoc param1, Object JavaDoc param2)
36         throws ParseException
37     {
38         if (param1 instanceof Complex)
39         {
40             if (param2 instanceof Complex)
41             {
42                 return sub((Complex)param1, (Complex)param2);
43             }
44             else if( param2 instanceof Number JavaDoc)
45             {
46                 return sub((Complex)param1, (Number JavaDoc)param2);
47             }
48         }
49         else if (param1 instanceof Number JavaDoc)
50         {
51             if (param2 instanceof Complex)
52             {
53                 return sub((Number JavaDoc)param1, (Complex)param2);
54             }
55             else if (param2 instanceof Number JavaDoc)
56             {
57                 return sub((Number JavaDoc)param1, (Number JavaDoc)param2);
58             }
59         }
60         throw new ParseException("Invalid parameter type");
61     }
62     
63
64     public Double JavaDoc sub(Number JavaDoc d1, Number JavaDoc d2)
65     {
66         return new Double JavaDoc(d1.doubleValue() - d2.doubleValue());
67     }
68     
69     public Complex sub(Complex c1, Complex c2)
70     {
71         return new Complex(c1.re() - c2.re(), c1.im() - c2.im());
72     }
73     
74     public Complex sub(Complex c, Number JavaDoc d)
75     {
76         return new Complex(c.re() - d.doubleValue(), c.im());
77     }
78
79     public Complex sub(Number JavaDoc d, Complex c)
80     {
81         return new Complex(d.doubleValue() - c.re(), -c.im());
82     }
83 }
84
Popular Tags