package com.example.calculater;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Calculate {
public String evaluate(String express) {
String expression = express;
double calculate = 0;
try {
List<String> infixExpression = depositList(expression);//中缀表达式
List<String> calculateExpression = parsExpression(infixExpression);//后缀表达式
calculate = calculate(calculateExpression);
}catch (RuntimeException e){
return "error";
}
if (calculate==0){
return "0";
} else {
BigDecimal bigDecimal = new BigDecimal(String.format("%.12f",calculate));//去掉前面多余的零
String result = bigDecimal.toString();
if(result.indexOf(".")>0){
result = result.replaceAll("0+?$","");//去掉后面无用的零
result = result.replaceAll("[.]$","");//如小数点后面全是零去掉小数点
}
return result;
}
}
public static List<String> parsExpression(List<String> list) {//方法:将得到的中缀表达式对应的转换后缀表达式对应的List
//定义两个栈
Stack<String> s1 = new Stack<String>(); // 符号栈
List<String> s2 = new ArrayList<String>(); // 储存中间结果的Lists2
for(String item: list ) {
if(item.matches("^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|[1-9]\\d*|0|-[1-9]\\d*\\.\\d*|-0\\.\\d*|-[1-9]\\d*$")) {//如果是一个数加入s2
s2.add(item);
} else if (item.equals("(")) {
s1.push(item);
} else if (item.equals(")")) {
while(!s1.peek().equals("(")) {//如果是右括号“)”,则依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一对括号丢弃
s2.add(s1.pop());
}
s1.pop();//将 ( 弹出 s1栈, 消除小括号
} else {
while(s1.size() != 0 && operation.getValue(s1.peek()) >= operation.getValue(item) ) {
s2.add(s1.pop());
}
s1.push(item);
}
}
while(s1.size() != 0) { //将s1中剩余的运算符依次弹出并加入s2
s2.add(s1.pop());
}
return s2;
}
public static List<String> depositList(String s) {
List<String> list = new ArrayList<String>();//定义一个List,存放中缀表达式 对应的内容
int i = 0;
String str;
char c;
do {
boolean isMinus = false;
if ((c=s.charAt(i))=='-'){
if (i==0 || s.charAt(i-1)=='('){
isMinus=true;
}
}
if(((c=s.charAt(i)) < 48 || (c=s.charAt(i)) > 57) && !isMinus) {
list.add("" + c);
i++;
} else {
str = ""; //先将str 置成"" '0'[48]->'9'[57]
do {
str += c;
i++;
}while(i < s.length() && (((c=s.charAt(i)) >= 48 && (c=s.charAt(i)) <= 57) || (c=s.charAt(i)) == '.'));
list.add(str);
}
}while(i < s.length());
return list;
}
public static double calculate(List<String> list) {
Stack<String> stack = new Stack<String>();// 创建栈
for (String item : list) {
if (item.matches("^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|[1-9]\\d*|0|-[1-9]\\d*\\.\\d*|-0\\.\\d*|-[1-9]\\d*$")) { //使用正则表达式匹配多位数
stack.push(item);
} else {
double num2 = Double.parseDouble(stack.pop()); // pop出两个数,并运算, 再入栈,如果空就赋值为零是为了让负数也能算
double num1 = Double.parseDouble(stack.pop());
double res = 0;
if (item.equals("+")) {
res = num1 + num2;
} else if (item.equals("-")) {
res = num1 - num2;
} else if (item.equals("×")) {
res = num1 * num2;
} else if (item.equals("÷")) {
res = num1 / num2;
} else {
throw new RuntimeException("运算符有误");
}
stack.push("" + res);
}
}
return Double.parseDouble(stack.pop());
}
}
//编写一个类 Operation 可以返回一个运算符 对应的优先级
class operation {
private static int Add = 1;
private static int Sub = 1;
private static int Mul = 2;
private static int Div = 2;
//写一个方法,返回对应的优先级数字
public static int getValue(String operation) {
int result = 0;
switch (operation) {
case "+":
result = Add;
break;
case "-":
result = Sub;
break;
case "×":
result = Mul;
break;
case "÷":
result = Div;
break;
default:
break;
}
return result;
}
}
Java中缀表达式求值(浮点数、负数都能用)
最新推荐文章于 2023-02-11 03:23:43 发布