四种基本的操作原理是将被转换成后缀缀表达式表达。然后计算。

转换思路和原则。可以参考将中缀表达式转化为后缀表达式

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 执行四则运算的更多相关文章

  1. java 执行 jar 包中的 main 方法

    java 执行 jar 包中的 main 方法 通过 OneJar 或 Maven 打包后 jar 文件,用命令: java -jar ****.jar执行后总是运行指定的主方法,如果 jar 中有多 ...

  2. java执行效率低,但效率就低吗?

    很多没用过java或者没怎么用过java的程序员都会说java执行效率低,这种言论时不时的在影响着我这个初级的java开发者. java执行效率低因如下几点导致(和C++比较): 1,java不允许内 ...

  3. Java执行main方法,异常为:could not find the main class.program will exit

    未解决. Java执行方法,异常为:could not find the main class.program will exitmain 原文地址:http://rogerfederer.iteye ...

  4. Java执行批处理.bat文件(有问题???求高手帮忙解答!!!)

                           Java执行批处理.bat文件(有问题???求高手帮忙解答!!!) 在项目开发中常常都会遇到需要在代码中调用批处理bat脚本,把自己在项目中遇到过的总结下 ...

  5. JAVA执行远端服务器的脚本

    JAVA执行远端服务器的脚本 问题描述 实现思路 技术要点 代码实现 问题描述 工作中遇到这样一个问题,我们的应用为了实现高可用会采取双机部署,拓扑图大致如下: 这种方案可以简单的保证高可用,即便应用 ...

  6. Java执行JavaScript脚本破解encodeInp()加密

    一:背景 在模拟登录某网站时遇到了用户名和密码被JS进行加密提交的问题,如图: 二:解决方法 1.我们首先需要获得该JS加密函数,一般如下: conwork.js var keyStr = " ...

  7. Java执行JavaScript代码

    Java执行JavaScript代码 这篇文章主要为大家详细介绍了Java执行JavaScript代码的具体操作方法,感兴趣的小伙伴们可以参考一下 我们要在Java中执行JavaScriptMetho ...

  8. Java执行shell遇到的各种问题

    1.判断子进程是否执行结束 有的时候我们用java调用shell之后,之后的操作要在Process子进程正常执行结束的情况下才可以继续,所以我们需要判断Process进程什么时候终止. Process ...

  9. java执行jar包出错:Unable to access jarfile

    java执行jar包出错:Unable to access jarfile 错误的原因有多种: 1.一般都是路径不正确.在Windows中,正确的路径类似于: java -jar "D:\W ...

随机推荐

  1. linux下远程管理利器-tmux

    linux下远程管理利器-tmux 1.控制键       控制键就是tmux的主键.当你在tmux环境下按下这个键的时候,tmux就会把你后面输入的指令,解析成它内置的功能.tmux默认的控制键是 ...

  2. hdu 2147 SG函数打表(手写也可以) 找规律

    kiki's game Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 40000/1000 K (Java/Others) Total ...

  3. 响应VC++ 标题栏右边的关闭按钮“红叉”

    击标题栏右边的关闭按钮“红叉”时,程序会向窗口发送WM_CLOSE消息,因此可以截取此消息在窗口关系前做一些提示或者是不允许点击时关闭程序 case WM_CLOSE: if (...) { Post ...

  4. 深入 CSocket 编程之阻塞和非阻塞模式

    有时,花上几个小时阅读.调试.跟踪优秀的源码程序,能够更快地掌握某些技术关键点和精髓.当然,前提是对这些技术大致上有一个了解. 我通过几个采用 CSocket 类编写并基于 Client/Server ...

  5. POJ3071-Football(概率DP+滚动数组)

    Football Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 2769   Accepted: 1413 Descript ...

  6. jconsole 连接 eclipse启动项目

    eclipse 启动java项目默认没有开启jmx远程查看功能,假设须要看项目执行的线程内存使用量等信息,能够在eclipse启动參数中添加: -Dcom.sun.management.jmxremo ...

  7. Android中九种dialog对话框代码

    public class MainActivity extends Activity { private static final int MAX_PROGRESS = 100; private st ...

  8. cocos2dx游戏开发学习笔记3-lua面向对象分析

    在lua中,能够通过元表来实现类.对象.继承等.与元表相关的方法有setmetatable().__index.getmetatable().__newindex. 详细什么是元表在这里就不细说了,网 ...

  9. select下拉菜单反显不可改动,且submit能够提交数据

    首先通过后台funcA()将下拉菜单反显不可改动的数据response到disable.jsp页面,disable.jsp: <script> var data1=${result.obj ...

  10. gradle多模块开发(转)

    参考文档:gradle的官方userguide.pdf文档的chapter 55和chapter 56.gradle的多模块或项目开发一定不会比maven差,在我看来!大的项目分成多个模块来开发是常事 ...