当前位置:网站首页>输入一个表达式(用字符串表示),求这个表达式的值。
输入一个表达式(用字符串表示),求这个表达式的值。
2022-07-01 05:39:00 【猿小蔡-Cool】
在刷算法题的时候,碰到一道题,记录一下,题目是这样的:
输入一个表达式(用字符串表示),求这个表达式的值。
保证字符串中的有效字符包括[‘0’-‘9’],‘+’,‘-’, ‘*’,‘/’ ,‘(’, ‘)’,‘[’, ‘]’,‘{’ ,‘}’。且表达式一定合法。
输入描述:
输入一个算术表达式
输出描述:
得到计算结果
输入:
3+2*{1+2*[-4/(8-6)+7]}
输出:
25
看了一下解法,如下:
Scanner scan = new Scanner(System.in);
String input = s;
input = input.replace("[","(");
input = input.replace("{","(");
input = input.replace("}",")");
input = input.replace("]",")");
ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("nashorn");
try {
System.out.println(scriptEngine.eval(input));
} catch (ScriptException e) {
throw new RuntimeException(e);
}
额,超出了我的想象,这个ScriptEngine这么神奇。了解了一下。
一般的用途主要是能解析通用的表达式就好,比如X >= 1(X作为参数传入)这样的表达式,也能利用js的函数语法,创造一个就像java的函数一样存在于内存中随时可以被调用的函数,更可以将js中的对象直接转换成java对象。
边栏推荐
- Web Security (IX) what is JWT?
- RecycleView的一些使用
- rust猜数字游戏
- [QT] QT after addition, subtraction, multiplication and division, two decimal places are reserved
- Vscode function annotation / file header annotation shortcut
- Summary of common components of applet
- Typeorm framework
- boot+jsp的高校社團管理系統(附源碼下載鏈接)
- 多表操作-外键级联操作
- Unity project experience summary
猜你喜欢

In depth understanding of condition source code interpretation and analysis of concurrent programming

Cockroachdb: the resistant geo distributed SQL database paper reading notes

How to create a progress bar that changes color according to progress

Mongodb學習篇:安裝後的入門第一課

Boot + jsp University Community Management System (with source Download Link)

Use and principle of AQS related implementation classes

从底层结构开始学习FPGA----RAM IP的定制与测试

了解 JVM 中几个相关问题 — JVM 内存布局、类加载机制、垃圾回收

使用 Nocalhost 开发 Rainbond 上的微服务应用

实战:redux的基本使用
随机推荐
More than one file was found with OS independent path ‘lib/armeabi-v7a/libyuv.so‘.
Data governance: data governance framework (Part I)
Is it safe for a novice to open a securities account?
Memtable for leveldb source code analysis
vsCode函数注解/文件头部注解快捷键
First defined here occurs during QT compilation. Causes and Solutions
Design and application of immutable classes
在Rainbond中一键部署高可用 EMQX 集群
Qt编写自定义控件-自绘电池
mysql 将毫秒数转为时间字符串
QT等待框制作
Use and principle of AQS related implementation classes
Summary of common components of applet
数据库连接池的简单实现
Brief description of activation function
Educational administration management system (free source code)
3D建模与处理软件简介 刘利刚 中国科技大学
[medical segmentation] u2net
Numeric amount plus comma; JS two methods of adding three digits and a comma to numbers; JS data formatting
Fiber Bragg grating (FBG) notes [1]: waveguide structure and Bragg wavelength derivation