KickJava   Java API By Example, From Geeks To Geeks.

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


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
10 package org.nfunk.jep.function;
11
12 import java.util.*;
13 import org.nfunk.jep.*;
14
15 /**
16  * This class serves mainly as an example of a function that accepts any
17  * number of parameters. Note that the numberOfParameters is initialized to
18  * -1.
19  */

20 public class Sum extends PostfixMathCommand
21 {
22     private Add addFun = new Add();
23     /**
24      * Constructor.
25      */

26     public Sum() {
27         // Use a variable number of arguments
28
numberOfParameters = -1;
29     }
30     
31     /**
32      * Calculates the result of summing up all parameters, which are assumed
33      * to be of the Double type.
34      */

35     public void run(Stack stack) throws ParseException {
36         
37         // Check if stack is null
38
if (null == stack) {
39             throw new ParseException("Stack argument null");
40         }
41         
42         Object JavaDoc param = stack.pop();
43         Number JavaDoc result;
44         if (param instanceof Number JavaDoc)
45             result = (Number JavaDoc) param;
46         else
47             throw new ParseException("Invalid parameter type");
48         
49         // repeat summation for each one of the current parameters
50
for(int i=1;i < curNumberOfParameters;++i)
51         {
52             // get the parameter from the stack
53
param = stack.pop();
54             if (param instanceof Number JavaDoc) {
55                 // calculate the result
56
result = addFun.add((Number JavaDoc) param,result);
57             } else {
58                 throw new ParseException("Invalid parameter type");
59             }
60                 
61             i++;
62         }
63         // push the result on the inStack
64
stack.push(result);
65     }
66 }
67
Popular Tags