0

I have written a project that calculates different functions like sine,MCM etc without using existing packages like math in java now I want to get an expression from the user in form of a string and then print out the result
like :

import java.util.Scanner;

public class Phase2main {

public static void main(String[] args) {

    Scanner s = new Scanner(System.in);
    String expression   ;
    double result = 0 ;

    System.out.println(" Enter your desired expression from the available functions ");

    expression = s.nextLine();


    System.out.println("Result is : " + result);                
 }
}

then it should run like this: Enter an Expression: ADD(DIV(SIN(FACT(3)),CEIL(TAN(MUL(1.5,FIB(4))))),GCD(2,10)) The Result is: 1.94

how can I make the program to identify my functions like CEIL and their input ? I've checked many of the similar questions but the ones that I found are rather libraries that are too complex for me to understand or do basic arithmetic without identifying functions and their inputs

so how can I write a simple evaluator for this specific problem?

Vicarious
  • 131
  • 18
  • You can achieve this by using [OGNL](http://commons.apache.org/proper/commons-ognl/). It is easy to use. You can create a context and eveluate expression with it. – bhdrkn Dec 05 '14 at 15:32
  • This is an incredibly broad question. If you want to just identify functions - use any parser (or write your own - there is a ton of guides out there). If you want help in evaluation as well - then this question is akin to "Help me write my own Wolfram Alpha!" – Ordous Dec 05 '14 at 15:35
  • Unless you find a library that conform to the syntax you need there is no simple solution to your problem. You have to write your own parser with the help of a parser generator like javacc, antlr or eclipse Xtext. – nomoa Dec 05 '14 at 15:35
  • so can you suggest a simple library ? i have looked at this https://github.com/uklimaschewski/EvalEx but I can't understand how to relate my result and input to that library – Vicarious Dec 05 '14 at 15:37
  • JavaCC : http://www.cs.rit.edu/~ats/java/html/skript/4__04.htmld/ or XText http://zverovich.net/2011/12/03/first-experience-with-xtext.html. Also you can read this http://stackoverflow.com/questions/7258538/free-java-library-for-evaluating-math-expressions. But I'm afraid none of this solution is what you call "simple library". – nomoa Dec 05 '14 at 15:41

3 Answers3

1

May be use JavaScript interpreter?

First create engine instance and init:

// Manager creates engines by mime/language names.
// It has own global scope for engiges created by it.
ScriptEngineManager manager = new ScriptEngineManager();
// Create JavaScript interpreter instance.
// (Nashorn is bundled JavaScript interpreter)
ScriptEngine scope = manager.getEngineByName("JavaScript");
// Define functions you need
String initialScript = "cos = Math.cos;" // ; or \n
    + "sin = Math.sin;"
    + "tg  = Math.tan;"
    + "PI  = Math.PI;"
// Any other function
    + "ctg = function (x) { return cos(x)/sin(x); };";
// ...

try {
    // Add these functions to scope
    scope.eval(initialScript);
} catch(ScriptException ex) {
    // Evaluating exceptions, syntax errors are thrown here
}

And then you can evaluate expressions in the "scope" many times:

try {
    double d = (double)scope.eval("sin(PI/2) + cos(PI/2)");
    System.out.println("Calculated: " + d);
} catch(ScriptException e) {
    // ...
}

Be warned:

  1. There is language interpreting - user can pass any script and...
  2. ... it can reduce perfomance of application.

You can also use, for example, Jython or JRuby as interpreter.

cybersoft
  • 1,453
  • 13
  • 31
  • what is scope ? I get compile error for an undefined type when I use it – Vicarious Dec 05 '14 at 18:27
  • thanks again something that I cant still do to your solution is that I want to to get the expression from the user as a string and then print the result out also I'm not using math package .I'm using functions I wrote for sin cos and others what else should I change in here ? http://paste.ubuntu.com/9387085/ – Vicarious Dec 05 '14 at 20:45
  • You can define fully own functions and constants as shown above. Em, what is COS.calcuCOS, etc and where it defined? – cybersoft Dec 05 '14 at 21:12
  • I've defined cos. calcuCOS in another class and It works alright – Vicarious Dec 05 '14 at 21:48
  • This the second phase of a project. first phase was to make a program that calculates all of the functions of java. lang math package without using the package itself (by using Taylor series and other means) the second phase is to write a program that receives an expression in form of a string made of phase 1 functions and prints the result – Vicarious Dec 05 '14 at 21:53
  • this is what should be seen when the program is executed – Vicarious Dec 05 '14 at 21:57
  • Enter an Expression: ADD(DIV(SIN(FACT(3)),CEIL(TAN(MUL(1.5,FIB(4))))),GCD(2,10)) //this what user enters or input – Vicarious Dec 05 '14 at 21:58
  • and this should be the output : =>> The Result is: 1.94 – Vicarious Dec 05 '14 at 22:00
  • You can add methods as so: `scope.put("cos", (Function)(double x) -> YourCos.cos(x));` – cybersoft Dec 05 '14 at 22:36
0

You could use the Java Scripting API, and for instance use JavaScript, or BeanShell (java like).

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByMimeType("text/javascript");
    try {
        engine.eval("print('Result: ' + java.lang.Math.sin(0.8))");
        double y = ((Number) engine.eval("java.lang.Math.sin(0.8)")).doubleValue();
    } catch (ScriptException ex) {
        Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
    }

JavaScript can use imports. As you can see, calling java is quite simple.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0

I'm not sure if there is any simple way to identify and evaluate generic inputed expressions without using libraries.

If you want to develop your own way to evaluate math expressions take a look on this page, it should show you the way to go: http://cogitolearning.co.uk/?p=565

And if you change your mind and want to use an library, check this link: Evaluating a math expression given in string form

I've done this when I built a java compiler, that way I could read and evaluate any expression, but it wasn't simple...

Community
  • 1
  • 1