GeverAL
GeverAL

Reputation: 21

rhino for equation solving in android studio

Im trying to make an app for school project. the propose of the app is to solve equuations, the program is working pretty good (it's using newtons method). when i did some research about how to make a string in to a code, ive found something called rhino, so now im using it to solve the equation the only problem is when im trying to enter the Math.pow(a, b) into the string i want to execute, string that look like this give me back this error:

String => "(float)2*Math.pow(NaN,2)-1"
----------------------------------------------
Error => "org.mozilla.javascript.EvaluatorException: missing ; before statement (<Unknown source>#1) in <Unknown source> at line number 1"

now I really didnt get rhino so good,so i tried to find any tutorial about it, and found nothing, any way, if any one how to make this work, i would really apriciate some help. Thanks Ido barel.

The full code if anyone need it.

private Object place_X_in_func(String raw_func, float num){
        String func = raw_func.replace(" ", "");
        String equation = "(float)";
        int i = 0;
        while(i < func.length()) {
            boolean isPow = false;
            char c = func.charAt(i);
            if(c == 'x' || c == 'X'){
                char v = func.charAt(func.indexOf(c)+1);
                if((int)v == 94){
                    char z = func.charAt(func.indexOf(v)+1);
                    equation += "Math.pow("+String.valueOf(num)+","+z+")";
                    i+= 3;
                    isPow = true;
                }
                else{
                    equation+= String.valueOf(num);
            }
            }
            else {
                equation += c;
            }
            if(!isPow){
                i += 1;
            }
            //System.out.println("Runned "+i+"of "+func.length());
        }
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("rhino");
        try {
            System.out.println("EQ => "+equation);
            Object result = engine.eval(";"+equation);
            System.out.println(result);
            return ("R:"+result);
        } catch (ScriptException e) {
            System.out.println(e.getMessage());
        }
        return  0;
    }

Upvotes: 0

Views: 220

Answers (1)

agermano
agermano

Reputation: 1719

Your string isn't valid javascript. Javascript has no datatype casting. If you remove the (float) at the beginning of your string it should work. The result of the expression 2*Math.pow(NaN,2)-1 in javascript is a number. The result will be returned to java as a java.lang.Double.

Upvotes: 1

Related Questions