1

The following code should be pretty self-evident. What I have made up so far to compute Y with variable x and some constants:

public static void main(String[] args) {
    int x=50;
    String str="100-x+200";
    str=str.replaceAll("x", Integer.toString(x));
    String [] arrComputeNumber = str.split("[-|+]");
    String [] arrComputeOperator = str.split("[\\d]");
    int y=Integer.parseInt(arrComputeNumber[0]);
    for (int i = 0; i < arrComputeOperator.length; i++) {
        if (arrComputeOperator[i].equals("-")) {
            y-=Integer.parseInt(arrComputeNumber[i+1]);
        } else if (arrComputeOperator[i].equals("+")) {
            y+=Integer.parseInt(arrComputeNumber[i+1]); 
        }
    }
    System.out.println("y="+y);
}

Unfortunately it doesn't work since str.split("[\\d]") extracts wrongly.

It it extracts correctly I assume that above code would function correctly. Anyway this implementation is merely trivial and doesn't take parenthesis or +- combination (which becomes minus), etc. into consideration. I haven't found any better ways. Do you know any better ways to evaluate string as mathematical expression in Java?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
ough
  • 549
  • 1
  • 6
  • 10

1 Answers1

1

You can use BeanShell. It is a Java interpreter.

Here is some code:

Interpreter interpreter = new Interpreter();
interpreter.eval("x = 50");
interpreter.eval("result = 100 - x + 200");
System.out.println(interpreter.get("result"));
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287