Java 执行四则运算
四种基本的操作原理是将被转换成后缀缀表达式表达。然后计算。
转换思路和原则。可以参考将中缀表达式转化为后缀表达式
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.regex.Pattern; public class Arithmetic {
//操作符stack
private Stack<String> operator = new Stack<String>();
//后缀表达式
private List<String> postFix = new ArrayList<String>(); private Pattern operatorPattern = Pattern.compile("[\\d\\.]");
private Pattern arithmeticPattern = Pattern.compile("[\\(\\)\\+\\-\\*\\/]"); //将中缀表达式换为后缀表达式
public void parse(String s) {
s = replace(s);
int j = 0;
for (int i = 0; i < s.length(); i++) {
String temp = s.substring(i, i + 1);
if (operatorPattern.matcher(temp).matches()) {
continue;
}
if (arithmeticPattern.matcher(temp).matches()) {
j = process(j, i, s, temp);
} else if (" ".equals(temp)) {
return;
}
}
if (j < s.length()) {
postFix.add(s.substring(j, s.length()));
}
while (!this.operator.isEmpty()) {
postFix.add(operator.pop());
}
} private String replace(String s) {
return s.replaceAll("\\s", "");
} private int process(int startIndex, int currentIndex, String str, String word) {
if (startIndex != currentIndex) {
postFix.add(str.substring(startIndex, currentIndex));
}
addOperator(word);
startIndex = currentIndex + 1;
if (startIndex > str.length()) {
startIndex = str.length();
}
return startIndex;
} public void addOperator(String operator) {
if ("(".equals(operator)) { } else if(")".equals(operator)) {
while (!this.operator.isEmpty()) {
String temp = this.operator.pop();
if ("(".equals(temp)) {
break;
} else {
postFix.add(temp);
} }
return;
} else if (!this.operator.isEmpty()) {
while(!this.operator.isEmpty()) {
String temp = this.operator.peek();
if (needPop(temp, operator)) {
this.postFix.add(this.operator.pop());
} else {
break;
}
}
}
this.operator.add(operator);
} public boolean needPop(String inStackTop, String current) {
return getLevel(current.charAt(0)) <= getLevel(inStackTop.charAt(0));
} public int getLevel(char operator) {
switch (operator) {
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
default:
return -1;
}
} public BigDecimal compute() {
Stack<BigDecimal> stack = new Stack<BigDecimal>();
for (int i=0; i < this.postFix.size(); i++) {
if (arithmeticPattern.matcher(postFix.get(i)).matches()) {
BigDecimal bd2 = stack.pop();
BigDecimal bd1 = stack.pop();
BigDecimal temp = compute(postFix.get(i).charAt(0), bd1, bd2);
stack.add(temp);
} else {
stack.add(new BigDecimal(postFix.get(i)));
}
}
return stack.pop();
} private BigDecimal compute(char operator, BigDecimal bd1, BigDecimal bd2) {
switch (operator) {
case '+':
return bd1.add(bd2);
case '-':
return bd1.subtract(bd2);
case '*':
return bd1.multiply(bd2);
case '/':
return bd1.divide(bd2);//应当使用bd1.divide(divisor, scale, roundingMode);
default:
return null;
}
} public static void main(String[] args) {
Arithmetic arithmetic = new Arithmetic();
arithmetic.parse("9+(3-1)*3+10/2");
System.out.println(arithmetic.postFix);
System.out.println(arithmetic.compute()); arithmetic = new Arithmetic();
arithmetic.parse("9+(3-1)*3+10/2+1000-200-(100+5-9/3)");
System.out.println(arithmetic.postFix);
System.out.println(arithmetic.compute()); arithmetic = new Arithmetic();
arithmetic.parse("9 + (3 - 1) * 3 + 10 / 2 + 1000 - 200 - ( 100 + 5 - 9 / 3)");
System.out.println(arithmetic.postFix);
System.out.println(arithmetic.compute());
}
}
Java 执行四则运算的更多相关文章
- java 执行 jar 包中的 main 方法
java 执行 jar 包中的 main 方法 通过 OneJar 或 Maven 打包后 jar 文件,用命令: java -jar ****.jar执行后总是运行指定的主方法,如果 jar 中有多 ...
- java执行效率低,但效率就低吗?
很多没用过java或者没怎么用过java的程序员都会说java执行效率低,这种言论时不时的在影响着我这个初级的java开发者. java执行效率低因如下几点导致(和C++比较): 1,java不允许内 ...
- Java执行main方法,异常为:could not find the main class.program will exit
未解决. Java执行方法,异常为:could not find the main class.program will exitmain 原文地址:http://rogerfederer.iteye ...
- Java执行批处理.bat文件(有问题???求高手帮忙解答!!!)
Java执行批处理.bat文件(有问题???求高手帮忙解答!!!) 在项目开发中常常都会遇到需要在代码中调用批处理bat脚本,把自己在项目中遇到过的总结下 ...
- JAVA执行远端服务器的脚本
JAVA执行远端服务器的脚本 问题描述 实现思路 技术要点 代码实现 问题描述 工作中遇到这样一个问题,我们的应用为了实现高可用会采取双机部署,拓扑图大致如下: 这种方案可以简单的保证高可用,即便应用 ...
- Java执行JavaScript脚本破解encodeInp()加密
一:背景 在模拟登录某网站时遇到了用户名和密码被JS进行加密提交的问题,如图: 二:解决方法 1.我们首先需要获得该JS加密函数,一般如下: conwork.js var keyStr = " ...
- Java执行JavaScript代码
Java执行JavaScript代码 这篇文章主要为大家详细介绍了Java执行JavaScript代码的具体操作方法,感兴趣的小伙伴们可以参考一下 我们要在Java中执行JavaScriptMetho ...
- Java执行shell遇到的各种问题
1.判断子进程是否执行结束 有的时候我们用java调用shell之后,之后的操作要在Process子进程正常执行结束的情况下才可以继续,所以我们需要判断Process进程什么时候终止. Process ...
- java执行jar包出错:Unable to access jarfile
java执行jar包出错:Unable to access jarfile 错误的原因有多种: 1.一般都是路径不正确.在Windows中,正确的路径类似于: java -jar "D:\W ...
随机推荐
- iOS 5 故事板入门(3)
原文: http://www.raywenderlich.com/5138/beginning-storyboards-in-ios-5-part-2 Segues 介绍 是时候在我们的故事板中加入更 ...
- 【IUML】支持向量机SVM
从1995年Vapnik等人提出一种机器学习的新方法支持向量机(SVM)之后,支持向量机成为继人工神经网络之后又一研究热点,国内外研究都很多.支持向量机方法是建立在统计学习理论的VC维理论和结构风险最 ...
- CF 327D - Block Tower 数学题 DFS 初看很难,想通了就感觉很简单
D. Block Tower time limit per test 2 seconds memory limit per test 256 megabytes input standard inpu ...
- 马航MH17事件将把普京逼入绝境?
据7月22日报道,马克兰东部民间武装22日凌晨将失事客机的"黑匣子"交给马来西亚方面.乌政府与民间武装允许在坠机地点附的小范围停火. 与此同一时候,联合国安理会21日通过决议,敦促 ...
- .NET Core 1.0.0 RC2
.NET Core 1.0.0 RC2 在.NET Core 1.0.0 RC2即将正式发布之际,我也应应景,针对RC2 Preview版本编写一个史上最简单的MVC应用.由于VS 2015目前尚不支 ...
- 程序缩小到托盘后系统就无法关机(解决方案)——处理WM_QUERYENDSESSION消息,并把它标识为处理过了
程序缩小到托盘后系统就无法关机(解决方案) 老帅 程序最小化到托盘后,会出现系统无法关闭的问题,常见于WinXP系统中,这里提供一个解决方案!一.解决 ...
- About Unixstickers - Unixstickers - stickers on unix, programming, software, development and open source
About Unixstickers - Unixstickers - stickers on unix, programming, software, development and open so ...
- 解决org.hibernate.LazyInitializationException: could not initialize proxy - no Session懒载入问题
问题描写叙述: Struts Problem Report Struts has detected an unhandled exception: Messages: could not initia ...
- DecimalFormat
public class TestDemo { public static void main(String[] args) { String format = new DecimalFormat(& ...
- 修改emlog后台登录路径的方法(转)
emlog后台登录地址的目录名称默认为admin,并且官方没有提供自定义后台登录入口名字的功能,这多少让我们觉得有些不安全,毕竟暴露一个网站的后台不是一件安全的事,今天就给您说下修改方法,增加一下网站 ...