java字符串数学公式运算
来源:互联网 发布:巨人网络私有化价格 编辑:程序博客网 时间:2024/06/02 20:14
在stackoverflow上找到了答案,可用的lib有BeanShell,ScriptEngineManager之类。但也有人写出了简单的:from: http://stackoverflow.com/a/26227947/2193455
public static double eval(final String str) { return new Object() { int pos = -1, ch; void nextChar() { ch = (++pos < str.length()) ? str.charAt(pos) : -1; } boolean eat(int charToEat) { while (ch == ' ') nextChar(); if (ch == charToEat) { nextChar(); return true; } return false; } double parse() { nextChar(); double x = parseExpression(); if (pos < str.length()) throw new RuntimeException("Unexpected: " + (char)ch); return x; } // Grammar: // expression = term | expression `+` term | expression `-` term // term = factor | term `*` factor | term `/` factor // factor = `+` factor | `-` factor | `(` expression `)` // | number | functionName factor | factor `^` factor double parseExpression() { double x = parseTerm(); for (;;) { if (eat('+')) x += parseTerm(); // addition else if (eat('-')) x -= parseTerm(); // subtraction else return x; } } double parseTerm() { double x = parseFactor(); for (;;) { if (eat('*')) x *= parseFactor(); // multiplication else if (eat('/')) x /= parseFactor(); // division else return x; } } double parseFactor() { if (eat('+')) return parseFactor(); // unary plus if (eat('-')) return -parseFactor(); // unary minus double x; int startPos = this.pos; if (eat('(')) { // parentheses x = parseExpression(); eat(')'); } else if ((ch >= '0' && ch <= '9') || ch == '.') { // numbers while ((ch >= '0' && ch <= '9') || ch == '.') nextChar(); x = Double.parseDouble(str.substring(startPos, this.pos)); } else if (ch >= 'a' && ch <= 'z') { // functions while (ch >= 'a' && ch <= 'z') nextChar(); String func = str.substring(startPos, this.pos); x = parseFactor(); if (func.equals("sqrt")) x = Math.sqrt(x); else if (func.equals("sin")) x = Math.sin(Math.toRadians(x)); else if (func.equals("cos")) x = Math.cos(Math.toRadians(x)); else if (func.equals("tan")) x = Math.tan(Math.toRadians(x)); else throw new RuntimeException("Unknown function: " + func); } else { throw new RuntimeException("Unexpected: " + (char)ch); } if (eat('^')) x = Math.pow(x, parseFactor()); // exponentiation return x; } }.parse();}
0 0
- java字符串数学公式运算
- java字符串数学公式运算
- Jep 解析字符串数学公式
- Jep解析字符串数学公式
- java字符串运算
- 计算字符串数学公式的结果
- 字符串数学公式计算类(C#)
- 计算字符串中的简单数学公式
- Java字符串异或运算
- Java 字符与字符串运算
- Java--字符和字符串运算
- 求和(数学公式推导、取余运算)
- 数学公式
- 数学公式
- 数学公式
- 数学公式
- 数学公式
- 数学公式
- Java Enum
- linux下设置共享目录
- Docker:设置代理proxy
- 6-27关于打飞机与自定义事件的总结
- Jquery 获取第一个子元素
- java字符串数学公式运算
- 项目中使用监听网络的广播,没网提示view显示,有网提示view隐藏,在网络状态切换时,在布局下方出现空白条的问题。
- Hive数据仓库笔记(一)
- 【Android】WebView设置背景色
- 模仿hibernate一级缓存session缓存机制
- Linux中debugfs的解析
- javaweb学习总结(十四)——JSP原理
- OKHttp源码解析(三)
- RTSP协议转换RTMP直播协议