1

I have the following xml file:

<?xml version="1.0" encoding="UTF-8"?>

<root>
    <eq1>-3.874999999999* Math.pow(x, 4.0) + 48.749999999993* Math.pow(x, 3.0)</eq1>
    <eq2>-0.166666666667* Math.pow(x, 4.0) + 2.166666666667* Math.pow(x, 3.0)</eq2>
</root>

I would like to parse these 2 equations and place them in variables for further calculations. The method I'm using currently is parsing them and placing them in a string, but it won't work as I need to perform the calculations using the equations.

Is there a better method I can use to work around this? Thanks in advance.

progdoc
  • 589
  • 3
  • 11
  • 24

2 Answers2

2

You can use JAXB to unmarshal the XML file to a custom Object with those fields.

Your object will probably look something like:

@XmlRootElement
public class Equations {

    String eq1;
    String eq2;

    // create getters and setters as well
    // and put the @XmlElement annotation on the setters
}

And then just use them from the Equations object. (equations.getEq1() for example);

Here's a really simple and quick intro to JAXB: http://www.mkyong.com/java/jaxb-hello-world-example/

Regarding the execution of the equations, one way is to parse the string and see which instructions and numbers you have and put them on a stack and then when everything is parsed, execute the operations (you'll have the numbers and operations on the stack). Maybe it's a little more work but It's definitely an interesting way to solve the problem.

Martin Spa
  • 1,494
  • 1
  • 24
  • 44
0

Try the BeanShell evaluator:

import bsh.EvalError;
import bsh.Interpreter;

public class BeanShellInterpreter {

  public static void main(String[] args) throws EvalError {

    Interpreter i = new Interpreter();  // Construct an interpreter
    i.set("x", 5);
    // Eval a statement and get the result
    i.eval("eq1 = (-3.874999999999* Math.pow(x, 4.0) + 48.749999999993* Math.pow(x, 3.0))");
    System.out.println( i.get("eq1") );
  }
}
Boris Pavlović
  • 63,078
  • 28
  • 122
  • 148
  • 1
    I think that the Sysout must be `System.out.println( i.get("bar") );` – lookfire Apr 11 '12 at 14:08
  • I'll look into it. This has to be implemented on a mobile app, so I think creating 2 variables with the respectful equations makes more sense, as a 250k library is quite large for an app. – progdoc Apr 11 '12 at 14:13