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

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

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. tbb 线程安全concurrent_queue的性能

    tbb实现了线程安全的queue,这样程序员既可以不用和那些lock,mutex,criticalsection打交道,又大大提高性能,太给力了..比较的结果见代码中的注释.结果可以看出代码足足少一半 ...

  2. Suse 创建NFS共享目录

    Suse 创建NFS共享目录 服务端的配置: 1.编辑nfs服务的配置文件 /software/suse11 *(rw,sync,no_root_squash,no_all_squash) 凝视: / ...

  3. Delphi中WebBrowser自动填表模板

    unit Unit1;interfaceuses  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, ...

  4. linux cent os putty 问题彻底解决办法

    出现乱码的根本原因: linux系统和putty使用的编码格式不一致. 解决办法: 1.首先使用命令查看linux当前使用的是什么编码格式 echo $LANG 返回的结果有如下几种情况:1)zh_C ...

  5. web desktop在线演示

    http://mydesk.sinaapp.com 基于extjs的web desktop应用框架. 1.跨浏览器 2.动态载入所需css,js文件 3.权限管理 4.支持多语种 5.支持asp,js ...

  6. JAVA的extends使用方法

    理解继承是理解面向对象程序设计的关键.在Java中,通过keywordextends继承一个已有的类,被继承的类称为父类(超类,基类),新的类称为子类(派生类).在Java中不同意多继承. (1)继承 ...

  7. 检查java class的版本号

    补丁总是会一遍又一遍的打,越打越多 有时候,就担心有人不小心把高版本的class打到低版本jre运行的环境中 简单写了点代码,检查文件夹中class的版本号 package org.wee.cv; i ...

  8. oracle 密码文件文件

    密码文件作用: 密码文件用于dba用户的登录认证. dba用户:具备sysdba和sysoper权限的用户,即oracle的sys和system用户. 本地登录: 1)操作系统认证: [oracle@ ...

  9. Tiny Mapper是一个.net平台开源的对象映射组件

    NET平台开源项目速览(14)最快的对象映射组件Tiny Mapper   阅读目录 1.Tiny Mapper基本介绍 2.Tiny Mapper 基本使用 3.Tiny Mapper 指定配置使用 ...

  10. poj 1220 NUMBER BASE CONVERSION(短除法进制转换)

    题目连接:1220 NUMBER BASE CONVERSION 题目大意:给出两个进制oldBase 和newBase, 以及以oldBase进制存在的数.要求将这个oldBase进制的数转换成ne ...