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

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

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. Hibernate(五)——经典解析一对一关联映射

    前面两篇介绍了多对一.一对多的映射.今天分享下一对一的关联映射关系.有两种策略可以实现一对一的关联映射:主键关联.唯一外键关联. 主键关联——两个表有完全相同的主键值,来表示它们的一对一的关系.数据库 ...

  2. IDL 自己定义功能

    function add,x,y return, x+y end pro sum x=1 y=2 print,add(x,y) end 版权声明:本文博客原创文章,博客,未经同意,不得转载.

  3. Linux Shell 之 Shell中的函数调用

    说起函数调用,相信大家也不会陌生,然而对于初学Shell的我来说,Shell中函数调用方式却有点让我不太习惯,自己也走了不少的弯路,因为传递参数时出了一个很“自然”的错误,也让我吃了不少的苦头,所以总 ...

  4. 注册Dev的帮助文件

    Download the CHM files from… Code: https://www.devexpress.com/Support/Documentation/download.xml?pla ...

  5. asp.net 下载任意格式文件 上传文件后台代码

    思路:将文件转化为流,输出到页面上的iframe中去 //下载附件逻辑 object DownLoad(NameValueCollection nv) { int attachId = nv[&quo ...

  6. 指尖上的电商---(3)Solr全文搜索引擎的配置

    接上篇,Solr的准备工作完毕后,本节主要介绍Solr的安装,事实上Solr不须要安装.直接下载就能够了      1.Solr配置 下载地址 :http://lucene.apache.org/so ...

  7. 一个好用的Dialog插件

    网页中常常须要弹出dialog,尽管非常多JS开源框架都提供这个功能,可是效果都不是非常好,比方easy-UI.改动样式这些又不是我擅长的,身边又没有美工兄弟,苦逼啊! (Easy-UI的BasicD ...

  8. ubuntu12 环境下编译freerdp

    有时候需要从linux环境下远程连接到windows的环境,可以采用freerdp.freerdp是一个linux下开源的工具,在Ubuntu下可以直接用 apt-get install freerd ...

  9. CMake Intro - CMakeLists.txt

    Notes:  directory structure:  cmake, cmake/Tutorial, cmake/Tutorial/MathLibs 1. File lists in cmake/ ...

  10. redis做RDB时请求超时case

        近期在排查redis做rdb时会有部分请求超时的case.初步推断是我们redisserver上开启了THP(Transparent Huge Pages).      1) Linux本身的 ...