输出一个JAVA函数,函数的入参为数据表达式,如入参为如 -2*3*-4 则函数的输出为@2*3*@4
时间: 2024-09-25 18:03:53 浏览: 27
你可以创建一个名为`evaluateExpression`的Java函数,它接受一个字符串作为输入,该字符串代表一个数学表达式,然后使用递归解析和计算来得到结果。这里是一个简单的示例,使用了栈来处理运算符优先级:
```java
import java.util.Stack;
public class ExpressionEvaluator {
private static final int PRECEDENCE_MULTIPLICATION = 2;
private static final String OPERATOR_MULTIPLICATION = "*";
public static double evaluate(String expression) {
return new ExpressionParser(expression).calculate();
}
private static class ExpressionParser {
private String input;
private Stack<Integer> operatorsStack = new Stack<>();
private StringBuilder resultBuilder = new StringBuilder();
public ExpressionParser(String expression) {
this.input = expression;
}
private double calculate() {
parseInput();
return Double.parseDouble(resultBuilder.toString());
}
private void parseInput() {
for (char c : input.toCharArray()) {
if (Character.isDigit(c)) {
addNumber(c);
} else if (c == '+' || c == '-') {
handleOperator('+');
} else if (c == '*' || c == '/') {
handleOperator(PRECEDENCE_MULTIPLICATION);
} else if (c == '(') {
operatorsStack.push(PRECEDENCE_MULTIPLICATION);
} else if (c == ')') {
while (!operatorsStack.isEmpty() && operatorsStack.peek() != '(') {
handleOperator(operatorsStack.pop());
}
}
}
while (!operatorsStack.isEmpty()) {
handleOperator(operatorsStack.pop());
}
}
private void handleOperator(int precedence) {
if (resultBuilder.length() > 0) {
resultBuilder.append(' ');
}
double right = Double.parseDouble(resultBuilder.toString());
resultBuilder.setLength(0);
resultBuilder.append(evaluateRightmost());
resultBuilder.append(OPERATOR_MULTIPLICATION);
resultBuilder.append(right);
}
private double evaluateRightmost() {
if (operatorsStack.isEmpty() || operatorsStack.peek() < precedence MULTIPLICATION) {
return Double.parseDouble(resultBuilder.toString());
}
double left = evaluateRightmost();
resultBuilder.deleteCharAt(resultBuilder.length() - 1); // remove the last operator
resultBuilder.append(left);
return left;
}
private void addNumber(char digit) {
resultBuilder.append(digit);
}
}
}
阅读全文