KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lsmp > djepExamples > AssignmentExample


1 /* @author rich
2  * Created on 26-Feb-2004
3  *
4  * This code is covered by a Creative Commons
5  * Attribution, Non Commercial, Share Alike license
6  * <a HREF="http://creativecommons.org/licenses/by-nc-sa/1.0">License</a>
7  */

8
9 package org.lsmp.djepExamples;
10 import org.nfunk.jep.*;
11
12 /**
13  * Examples using assignment
14  */

15 public class AssignmentExample {
16
17     public static void main(String JavaDoc args[])
18     {
19         // standard initilisation
20
JEP j = new JEP();
21         j.addStandardConstants();
22         j.addStandardFunctions();
23         j.addComplex();
24         j.setAllowUndeclared(true);
25         j.setImplicitMul(true);
26
27         // swith assignment facilities on
28
j.setAllowAssignment(true);
29
30         // parse assignment equations
31
j.parseExpression("x=3");
32         // evaluate it - no need to save the value returned
33
j.getValueAsObject();
34         // parse a second equation
35
j.parseExpression("y=2");
36         j.getValueAsObject();
37
38         // an equation involving above variables
39
j.parseExpression("x^y");
40         Object JavaDoc val3 = j.getValueAsObject();
41         System.out.println("Value is "+val3);
42         
43         try
44         {
45             // Alternative syntax
46
Node node1 = j.parse("z=i*pi");
47             j.evaluate(node1);
48             Node node2 = j.parse("exp(z)");
49             Object JavaDoc val2 = j.evaluate(node2);
50             System.out.println("Value: "+val2);
51             
52             // getting and setting variable values
53
Node node3 = j.parse("z=x^y");
54             j.setVarValue("x",new Double JavaDoc(2));
55             j.setVarValue("y",new Double JavaDoc(3));
56             j.evaluate(node3);
57             System.out.println(j.getVarValue("z")); // prints 8
58
}
59         catch(ParseException e) {
60             System.out.println("Error with parsing");
61         }
62         catch(Exception JavaDoc e) {
63             System.out.println("Error with evaluation");
64         }
65     }
66 }
67
Popular Tags