计算器
一、封装类
public static void main(String[] args) throws Exception { ScriptEngine js = new ScriptEngineManager().getEngineByName("JavaScript"); System.out.println(js.eval("(-2+3*5) + 30*10%".replaceAll("%","/100"))); }
二、原创计算器工具类
package com;
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
public class Calculate {
public static void main(String[] args) throws Exception{
System.out.println(getResult("-2+3*5+2*5--1*5"));
}
private static String getResult(String formula) throws Exception{
formula = formula.replace("(","(");
formula = formula.replace(")",")");
String reg = "[0-9\\\\.*%+()/-]*";
if(!formula.matches(reg)){
return "";
}
int leftCount = 0;
int rightCount = 0;
for(int i=0;i<formula.length();i++){
int left = formula.indexOf("(",i);
if(left!=-1){
leftCount++;
i = left;
}else{
break;
}
}
for(int i=0;i<formula.length();i++){
int right = formula.indexOf(")",i);
if(right!=-1){
rightCount++;
i = right;
}else{
break;
}
}
if(leftCount!=rightCount){
return "";
}
String formulaResult = formula;
formulaResult = getBrackets(formulaResult);
formulaResult = formulaResult.replace(formulaResult, getResultDetail(formulaResult));
return new BigDecimal(formulaResult).setScale(2,BigDecimal.ROUND_HALF_UP).toString();
}
//处理表达式小括号
public static String getBrackets(String formula) throws Exception{
if(formula.contains("(")){
int left = formula.lastIndexOf("(");
int right = formula.indexOf(")",left);
String formulaTemp = formula.substring(left,right+1);
String result = getResultDetail(formulaTemp);
formula = formula.replace(formulaTemp,result);
formula = getBrackets(formula);
}
return formula;
}
//计算表达式
public static String getResultDetail(String formula) throws Exception{
formula = formula.replace("(","");
formula = formula.replace(")","");
//处理百分号
List<Integer> percentList = new LinkedList<Integer>();
for(int i=0;i<formula.length();i++){
int percent = formula.indexOf("%",i);
if(percent!=-1){
percentList.add(percent);
i=percent;
}else{
break;
}
}
String formulaTemp = formula;
for(int i=0;i<percentList.size();i++){
String percentNum = formula.substring(0,percentList.get(i));
int sub = percentNum.lastIndexOf("-");
int add = percentNum.lastIndexOf("+");
int mul = percentNum.lastIndexOf("*");
int div = percentNum.lastIndexOf("/");
int num = Integer.max(Integer.max(Integer.max(sub,add),mul),div);
String numStr = formula.substring(num+1,percentList.get(i));
formulaTemp = formulaTemp.replace(numStr+"%",new BigDecimal(numStr).multiply(
new BigDecimal("0.01")).setScale(4,BigDecimal.ROUND_HALF_UP).toString());
}
formula = formulaTemp;
String formulaResult = formula;
formulaResult = calculateFirst(formulaResult);
formulaResult = calculateSecond(formulaResult);
return formulaResult;
}
//计算表达式所有乘除
public static String calculateFirst(String formula) throws Exception{
if(hasFirst(formula)){
formula = getFirst(formula);
formula = calculateFirst(formula);
}
return formula;
}
//计算表达式所有加减
public static String calculateSecond(String formula) throws Exception{
if(hasSecond(formula)){
formula = getSecond(formula);
formula = calculateSecond(formula);
}
return formula;
}
//判断表达式是否有乘除
public static boolean hasFirst(String formula) throws Exception{
int mul = formula.indexOf("*");
int div = formula.indexOf("/");
int max = Integer.max(mul,div);
boolean flag = false;
if(max != -1){
flag = true;
}
return flag;
}
//判断表达式是否有加减
public static boolean hasSecond(String formula) throws Exception{
int sub = formula.indexOf("-")==0?formula.indexOf("-",1):formula.indexOf("-");
int add = formula.indexOf("+");
int max = Integer.max(sub,add);
boolean flag = false;
if(max != -1){
flag = true;
}
return flag;
}
//计算表达式乘除,返回之后的表达式
public static String getFirst(String formula) throws Exception{
int mul = formula.indexOf("*");
int div = formula.indexOf("/");
int min = Integer.min(mul,div);
min = min==-1?Integer.max(mul,div):min;
String formulaResult = formula;
List<String > list = getFormula(formula,min);
BigDecimal result = bigDecimalCal(new BigDecimal(list.get(1)),new BigDecimal(list.get(2)),list.get(0).charAt(0));
formulaResult = formulaResult.replace(list.get(1) + list.get(0) + list.get(2), result.toString());
return formulaResult;
}
//计算表达式加减,返回之后的表达式
public static String getSecond(String formula) throws Exception{
int sub = formula.indexOf("-")==0?formula.indexOf("-",1):formula.indexOf("-");
int add = formula.indexOf("+");
int min = Integer.min(sub,add);
min = min==-1?Integer.max(sub,add):min;
String formulaResult = formula;
List<String > list = getFormula(formula,min);
BigDecimal result = bigDecimalCal(new BigDecimal(list.get(1)),new BigDecimal(list.get(2)),list.get(0).charAt(0));
formulaResult = formulaResult.replace(list.get(1) + list.get(0) + list.get(2), result.toString());
return formulaResult;
}
//找出两个参数及运算符
public static List<String> getFormula(String formula, int n) throws Exception{
List<String> list = new LinkedList<String>();
list.add(formula.charAt(n) + "");
String leftStr = formula.substring(0,n);
String rightStr = formula.substring(n+1);
int leftSub = leftStr.lastIndexOf("-");
int leftAdd = leftStr.lastIndexOf("+");
int leftMul = leftStr.lastIndexOf("*");
int leftDiv = leftStr.lastIndexOf("/");
int leftNum = Integer.max(Integer.max(Integer.max(leftSub,leftAdd),leftMul),leftDiv);
list.add(formula.substring(leftNum==0?leftNum:leftNum+1,n));
int rightSub = rightStr.indexOf("-")==0?rightStr.indexOf("-",1):rightStr.indexOf("-");
int rightAdd = rightStr.indexOf("+");
int rightMul = rightStr.indexOf("*");
int rightDiv = rightStr.indexOf("/");
int rightNum = -1;
List<Integer> rightList = new LinkedList<Integer>();
if(rightSub!=-1){
rightList.add(rightSub);
}
if(rightAdd!=-1){
rightList.add(rightAdd);
}
if(rightMul!=-1){
rightList.add(rightMul);
}
if(rightDiv!=-1){
rightList.add(rightDiv);
}
for(int i=0;i<rightList.size();i++){
if(rightNum == -1){
rightNum = rightList.get(i);
}else if(rightList.get(i)<rightNum){
rightNum = rightList.get(i);
}
}
list.add(formula.substring(n+1,rightNum == -1?formula.length():n+1+rightNum));
return list;
}
//计算制定两个参数及运算符
public static BigDecimal bigDecimalCal(BigDecimal a1, BigDecimal a2, char operator) throws Exception{
switch (operator){
case '+':
return a1.add(a2);
case '-':
return a1.subtract(a2);
case '*':
return a1.multiply(a2);
case '/':
return a1.divide(a2,20,BigDecimal.ROUND_HALF_UP);
default:
break;
}
throw new Exception("illegal operator!");
}
}