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

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

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. 用C++设计一个不能被继承的类(用私有构造函数+友元函数)

    题目:用C++设计一个不能被继承的类. 分析:这是Adobe公司2007年校园招聘的最新笔试题.这道题除了考察应聘者的C++基本功底外,还能考察反应能力,是一道很好的题目. 在Java中定义了关键字f ...

  2. Android - JNI静态(static)载入OpenCV

    JNI静态(static)载入OpenCV 本文地址: http://blog.csdn.net/caroline_wendy 步骤: 1. 准备OpenCV-Android库 复制OpenCV的sd ...

  3. Android获得Manifest在&lt;meta-data&gt;元件的值

    前段时间攻略完成游戏开发项目.其中用于包装散装. 目前市场上的网络不提交.但是,通过设置Manifest中的Meta_data>去获得相关參数,游戏ID号改变.游戏ID改变,然后游戏内容就改变. ...

  4. vc 基于对话框多线程编程实例——线程之间的通信

     vc基于对话框多线程编程实例——线程之间的通信 实例:

  5. linux命令笔记之ls

    假设要将全部的命令以一篇博客持续更新的方式去展现,将来在查找的时候非常不方便.出于这种考虑.将来将非常多命令都分开记录. 这里,一些基础使用方法都不做太多说明.主要记录下平时经经常使用到的一些命令. ...

  6. WebService的相关使用

    近期公司项目使用WebService ,这里简单做个总结. 事实上详细使用细节有些情况下须要改,还须要看实际情况,须要与server联调,详细沟通. 比方公司连接,非要把envelope.dotNet ...

  7. UIImagePickerController本地化控件文字

    在使用UIImagePickerController时候,你会发如今选择照片或者拍照的时候,界面的很多控件都是英文的,比方"Cancel","Choose"等. ...

  8. MySQL在一台db服务器上面如何启动多个实例

    安装过程省略过,源码安装请参考http://write.blog.csdn.net/postlist/1609043/all 整理自己的文档,发现以前做的例子,share下,欢迎大家提出改进意见. 一 ...

  9. cocos2D(四)---- CCSprite

    在介绍CCSprite之前,先要理解游戏开发中的一个核心概念:精灵.精灵也称为游戏对象,它能够用来表示游戏中的不论什么物体,比方敌人.子弹.甚至是一个背景图片.一段文字.CCSprite能够说是在co ...

  10. spring配置日志

    原文:http://blog.csdn.net/xiejx618/article/details/41698913 参考:http://spring.io/blog/2009/12/04/loggin ...