如何评估以字符串形式给出的数学表达式? [英] How to evaluate a math expression given in string form?

查看:26
本文介绍了如何评估以字符串形式给出的数学表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 Java 例程来评估来自 String 值的数学表达式,例如:

I'm trying to write a Java routine to evaluate math expressions from String values like:

  1. 5+3"
  2. 10-40"
  3. (1+10)*3"

我想避免大量的 if-then-else 语句.我该怎么做?

I want to avoid a lot of if-then-else statements. How can I do this?

推荐答案

使用 JDK1.6,您可以使用内置的 Javascript 引擎.

With JDK1.6, you can use the built-in Javascript engine.

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));
    } 
}

这篇关于如何评估以字符串形式给出的数学表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆