当前位置:网站首页>输入一个表达式(用字符串表示),求这个表达式的值。
输入一个表达式(用字符串表示),求这个表达式的值。
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对象。
边栏推荐
- 我从技术到产品经理的几点体会
- boot+jsp的高校社團管理系統(附源碼下載鏈接)
- Speed regulation and stroke control based on Ti drv8424 driving stepper motor
- In depth understanding of condition source code interpretation and analysis of concurrent programming
- Usage and principle of synchronized
- Data governance: data governance management (Part V)
- 如何创建一个根据进度改变颜色的进度条
- Boot + jsp University Community Management System (with source Download Link)
- Fiber Bragg grating (FBG) notes [1]: waveguide structure and Bragg wavelength derivation
- 激活函数简述
猜你喜欢
![[RootersCTF2019]babyWeb](/img/b4/aa8f8e107a9dacbace72d4717b1834.png)
[RootersCTF2019]babyWeb

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

Speed regulation and stroke control based on Ti drv8424 driving stepper motor

ssm+mysql二手交易网站(论文+源码获取链接)

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

Day 05 - file operation function

Txncoordsender of cockroachdb distributed transaction source code analysis
![[RootersCTF2019]babyWeb](/img/b4/aa8f8e107a9dacbace72d4717b1834.png)
[RootersCTF2019]babyWeb

Leetcode top 100 questions 1 Sum of two numbers

One click deployment of highly available emqx clusters in rainbow
随机推荐
rust猜数字游戏
LRU cache for leveldb source code analysis
How to create a progress bar that changes color according to progress
tar命令
El cascade echo failed; El cascader does not echo
In depth understanding of condition source code interpretation and analysis of concurrent programming
Fluentd is easy to use. Combined with the rainbow plug-in market, log collection is faster
新手在挖财开通证券账户安全吗?
Educational administration management system (free source code)
boot+jsp的高校社團管理系統(附源碼下載鏈接)
移动端常用解决方案
Leetcode top 100 question 2 Add two numbers
Floweable source code annotation (40) class delegation
What is the at instruction set often used in the development of IOT devices?
Qt编写自定义控件-自绘电池
excel高级绘图技巧100讲(一)-用甘特图来展示项目进度情况
【QT】qt加减乘除之后,保留小数点后两位
Unity 使用Sqlite
Detailed explanation of set
Mongodb学习篇:安装后的入门第一课