日常记录
package com.example.websktdemo01;
import java.math.BigDecimal;
import java.util.Stack;
public class ExpressionEvaluator {
// 判断字符是否为操作符
private static boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
// 获取操作符的优先级
private static int getPrecedence(char operator) {
switch (operator) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return -1;
}
}
// 执行运算
private static BigDecimal performOperation(BigDecimal a, BigDecimal b, char operator) {
switch (operator) {
case '+':
return a.add(b);
case '-':
return a.subtract(b);
case '*':
return a.multiply(b);
case '/':
if (b.compareTo(BigDecimal.ZERO) == 0) {
throw new ArithmeticException("Division by zero");
}
return a.divide(b, 10, BigDecimal.ROUND_HALF_UP); // 10位小数,四舍五入
default:
return BigDecimal.ZERO;
}
}
// 计算表达式的值
public static BigDecimal evaluateExpression(String expression) {
Stack<BigDecimal> values = new Stack<>(); // 用于存储操作数
Stack<Character> operators = new Stack<>(); // 用于存储操作符
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
// 跳过空格
if (c == ' ') continue;
// 如果当前字符是数字或小数点
if (Character.isDigit(c) || c == '.') {
StringBuilder sb = new StringBuilder();
while (i < expression.length() && (Character.isDigit(expression.charAt(i)) || expression.charAt(i) == '.')) {
sb.append(expression.charAt(i++));
}
i--; // 调整索引,因为外层循环也会增加i
values.push(new BigDecimal(sb.toString()));
}
// 如果当前字符是左括号
else if (c == '(') {
operators.push(c);
}
// 如果当前字符是右括号
else if (c == ')') {
while (operators.peek() != '(') {
BigDecimal b = values.pop();
BigDecimal a = values.pop();
char op = operators.pop();
values.push(performOperation(a, b, op));
}
operators.pop(); // 弹出左括号
}
// 如果当前字符是操作符
else if (isOperator(c)) {
while (!operators.isEmpty() && getPrecedence(operators.peek()) >= getPrecedence(c)) {
BigDecimal b = values.pop();
BigDecimal a = values.pop();
char op = operators.pop();
values.push(performOperation(a, b, op));
}
operators.push(c);
}
}
// 处理剩余的操作符
while (!operators.isEmpty()) {
BigDecimal b = values.pop();
BigDecimal a = values.pop();
char op = operators.pop();
values.push(performOperation(a, b, op));
}
// 最终栈中只会剩下一个值,那就是表达式的结果
return values.pop();
}
public static void main(String[] args) {
String expression = "8/(10-20)*0.0618"; //
BigDecimal result = evaluateExpression(expression);
System.out.println("Result of the expression '" + expression + "' is: " + result);
}
}