Equation parsing "100-x+200" and evaluating its value in java
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?
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"));
精彩评论