Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Wednesday, July 29, 2009

Sample Program Using JEP.

Hi friends,
Today I would like to share a program that uses Java Expressioin Parser(JEP).

Logic Of the program: Addition Of three numbers.

Code:

package jeptrial;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.singularsys.jep.Jep;

public class MainClass {
public MainClass() throws IOException {
Jep jep = new Jep();
Object o = null;
System.out.println("Enter value for a,b and c");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(System.in));
String st1 = bufferedReader.readLine();
int a = Integer.parseInt(st1);
String st2 = bufferedReader.readLine();
int b = Integer.parseInt(st2);
String st3 = bufferedReader.readLine();
int c = Integer.parseInt(st3);
try {
jep.addVariable("value1", a);
jep.addVariable("value2", b);
jep.addVariable("value3", c);

jep.parse("value1+value2+value3");
o = jep.evaluate();
System.out.println("The sum of the three numbers is " + o);
} catch (Exception e) {
// TODO: handle exception
System.out.println("Exception :" + e);
}

}

public static void main(String[] args) throws IOException {
MainClass mainClass = new MainClass();
}
}

Output:

Enter value for a,b and c
1
2
3
The sum of the three numbers is 6.0

1 comment:

Chandrasekar said...

This works for negative numbers too!
But it won't work for floating point numbers