Java字符串到数学方程 [英] Java string to math equation

查看:80
本文介绍了Java字符串到数学方程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现函数 public int eval(String infix){...}
,当我像这样使用它时:

I need to implement function public int eval(String infix) {...} and when I use this like this:

eval("3+2*(4+5)") 

我必须收到21。

算术表达式可以包含'+','*'和括号。

The arithmetic expression can contain '+', '*' and parentheses.

那么,我怎样才能将其转换为数学方程? 我不能使用非标准库。

So, how can I convert this to math equation? I can't use non-standard libs.

更新:
找到解决方案。

这是2种方式:波兰表示法并使用ScriptEngine。

推荐答案

信不信由你,使用JDK1.6,您可以使用内置的Javascript引擎。根据您的需求进行定制。

Believe it or not, with JDK1.6, you can use the built-in Javascript engine. Customise to suit your needs.

确保您拥有这些进口产品......

Make sure you have these imports...

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

代码:

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String infix = "3+2*(4+5)";
System.out.println(engine.eval(infix));

这篇关于Java字符串到数学方程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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