我试图写一个Java例程来计算数学表达式从字符串值,如:
"5 + 3" "10-4 * 5" "(1 + 10) * 3"
我想避免很多如果-then-else语句。 我该怎么做呢?
我试图写一个Java例程来计算数学表达式从字符串值,如:
"5 + 3" "10-4 * 5" "(1 + 10) * 3"
我想避免很多如果-then-else语句。 我该怎么做呢?
当前回答
看来应该由JEP来做这项工作
其他回答
如果Java应用程序已经访问了数据库,则无需使用任何其他jar,就可以轻松地计算表达式。
一些数据库要求你使用一个虚拟表(例如,Oracle的“dual”表),而另一些数据库则允许你在不从任何表中“选择”的情况下计算表达式。
例如,在Sql Server或Sqlite中
select (((12.10 +12.0))/ 233.0) amount
在Oracle中
select (((12.10 +12.0))/ 233.0) amount from dual;
使用DB的优点是可以同时计算多个表达式。此外,大多数DB将允许您使用高度复杂的表达式,也将有许多额外的函数,可以在必要时调用。
但是,如果需要分别计算许多单个表达式,性能可能会受到影响,特别是当DB位于网络服务器上时。
下面通过使用Sqlite内存数据库在一定程度上解决了性能问题。
下面是一个完整的Java工作示例
Class. forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite::memory:");
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery( "select (1+10)/20.0 amount");
rs.next();
System.out.println(rs.getBigDecimal(1));
stat.close();
conn.close();
当然,您可以扩展上面的代码以同时处理多个计算。
ResultSet rs = stat.executeQuery( "select (1+10)/20.0 amount, (1+100)/20.0 amount2");
如果我们要实现它,那么我们可以使用下面的算法
While there are still tokens to be read in, 1.1 Get the next token. 1.2 If the token is: 1.2.1 A number: push it onto the value stack. 1.2.2 A variable: get its value, and push onto the value stack. 1.2.3 A left parenthesis: push it onto the operator stack. 1.2.4 A right parenthesis: 1 While the thing on top of the operator stack is not a left parenthesis, 1 Pop the operator from the operator stack. 2 Pop the value stack twice, getting two operands. 3 Apply the operator to the operands, in the correct order. 4 Push the result onto the value stack. 2 Pop the left parenthesis from the operator stack, and discard it. 1.2.5 An operator (call it thisOp): 1 While the operator stack is not empty, and the top thing on the operator stack has the same or greater precedence as thisOp, 1 Pop the operator from the operator stack. 2 Pop the value stack twice, getting two operands. 3 Apply the operator to the operands, in the correct order. 4 Push the result onto the value stack. 2 Push thisOp onto the operator stack. While the operator stack is not empty, 1 Pop the operator from the operator stack. 2 Pop the value stack twice, getting two operands. 3 Apply the operator to the operands, in the correct order. 4 Push the result onto the value stack. At this point the operator stack should be empty, and the value stack should have only one value in it, which is the final result.
我想无论你用什么方法做这个都会涉及到很多条件命题。但是对于单个操作,比如在你的例子中,你可以将它限制为4个if语句
String math = "1+4";
if (math.split("+").length == 2) {
//do calculation
} else if (math.split("-").length == 2) {
//do calculation
} ...
当你想要处理像“4+5*6”这样的多个操作时,它会变得更加复杂。
如果你试图构建一个计算器,那么我建议分别传递计算的每个部分(每个数字或运算符),而不是作为一个单一的字符串。
使用带有代码注入处理的JDK1.6 Javascript引擎尝试下面的示例代码。
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class EvalUtil {
private static ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
public static void main(String[] args) {
try {
System.out.println((new EvalUtil()).eval("(((5+5)/2) > 5) || 5 >3 "));
System.out.println((new EvalUtil()).eval("(((5+5)/2) > 5) || true"));
} catch (Exception e) {
e.printStackTrace();
}
}
public Object eval(String input) throws Exception{
try {
if(input.matches(".*[a-zA-Z;~`#$_{}\\[\\]:\\\\;\"',\\.\\?]+.*")) {
throw new Exception("Invalid expression : " + input );
}
return engine.eval(input);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}
对于JDK1.6,您可以使用内置的Javascript引擎。
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class Test {
public static void main(String[] args) throws ScriptException {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String foo = "40+2";
System.out.println(engine.eval(foo));
}
}