用java写一个函数计算式
时间: 2023-03-26 14:03:25 浏览: 76
好的,我可以回答这个问题。以下是一个用 Java 编写的计算器函数示例:
public static double calculate(String expression) {
Stack<Double> stack = new Stack<>();
String[] tokens = expression.split(" ");
for (String token : tokens) {
if (token.equals("+")) {
double operand2 = stack.pop();
double operand1 = stack.pop();
stack.push(operand1 + operand2);
} else if (token.equals("-")) {
double operand2 = stack.pop();
double operand1 = stack.pop();
stack.push(operand1 - operand2);
} else if (token.equals("*")) {
double operand2 = stack.pop();
double operand1 = stack.pop();
stack.push(operand1 * operand2);
} else if (token.equals("/")) {
double operand2 = stack.pop();
double operand1 = stack.pop();
stack.push(operand1 / operand2);
} else {
stack.push(Double.parseDouble(token));
}
}
return stack.pop();
}
这个函数接受一个字符串表达式作为参数,例如 "2 + 3 * 4 - 5 / 2",并返回计算结果。它使用一个栈来实现计算,遇到数字就入栈,遇到运算符就弹出栈顶的两个数字进行计算,并将结果入栈。最后栈中剩下的数字就是计算结果。