Error with Equation parsing (java) -


i have code:

public class parse {     static double eval(string exp) {         scriptenginemanager mgr = new scriptenginemanager();         scriptengine engine = mgr.getenginebyname("javascript");         string stringresult = null;         try {             arraylist<variable> vars = askforvars(parse1(exp));             arraylist<string> usednames = new arraylist<string>();             (variable v : vars) {                 if (!usednames.contains(v.name)) {                     stringresult = replacestring(exp, v.name, "" + v.valueused);                     usednames.add(v.name);                 }                 return double.parsedouble(engine.eval(stringresult.tostring())                         .tostring());             }         } catch (exception ex) {             ex.printstacktrace();         }         return 0.0;     }      static arraylist<variable> parse1(string exp) {         arraylist<variable> variables = new arraylist<variable>();         scriptenginemanager mgr = new scriptenginemanager();         scriptengine engine = mgr.getenginebyname("javascript");         string stringresult;         try {             stringresult = exp;             (character c : stringresult.tochararray()) {                 if (c.isletter(c)) {                     variables.add(new variable(c.tostring(), 1.0));                 }             }         } catch (exception ex) {             ex.printstacktrace();         }         return variables;     }      static arraylist<variable> askforvars(arraylist<variable> as) {         arraylist<variable> result = new arraylist<variable>();         arraylist<string> usednames = new arraylist<string>();         (variable v : as) {             if (!usednames.contains(v.name)) {                 system.out.print("value of " + v.name + ": ");                 double input = double.parsedouble(messageutil.getinput());                 result.add(new variable(v.name, input));                 usednames.add(v.name);             }         }         return result;     }      static string replacestring(string s, string from, string to) {         return s.replaceall(from, to);     } } 

it ok when have 1 variable (eg: 2x, 3x+2x or on) problem comes when use more 1 (eg: x+y, 3x-3y, or on).

this error:

value of x: 3 value of y: 4 javax.script.scriptexception: sun.org.mozilla.javascript.internal.ecmaerror: referenceerror: "y" not defined. (#1) in @ line number 1 @ com.sun.script.javascript.rhinoscriptengine.eval(rhinoscriptengine.java:156) @ com.sun.script.javascript.rhinoscriptengine.eval(rhinoscriptengine.java:170) @ javax.script.abstractscriptengine.eval(abstractscriptengine.java:247) @ com.company.parse.eval(parse.java:24) @ com.company.messageutil.createexp(messageutil.java:97) @ com.company.main.main(main.java:28) x+y resolves to: 0.0


Popular posts from this blog