用逆波兰表达式写一个加减乘除的计算器 用Java
时间: 2023-11-22 14:05:52 浏览: 85
安卓作业—-慕课移动互联网作业7使用逆波兰式实现处理加减乘除符合运算的计算器
好的,我可以为你编写一个逆波兰表达式计算器,在Java语言中实现。以下是代码:
import java.util.Stack;
public class ReversePolishCalculator {
public static double calculate(String[] tokens) {
Stack<Double> stack = new Stack<Double>();
for (String token : tokens) {
if (isNumber(token)) {
stack.push(Double.valueOf(token));
} else {
double operand2 = stack.pop();
double operand1 = stack.pop();
double result = performOperation(token.charAt(0), operand1, operand2);
stack.push(result);
}
}
return stack.pop();
}
private static boolean isNumber(String token) {
try {
Double.parseDouble(token);
return true;
} catch (NumberFormatException ex) {
return false;
}
}
private static double performOperation(char operator, double operand1, double operand2) {
switch (operator) {
case '+':
return operand1 + operand2;
case '-':
return operand1 - operand2;
case '*':
return operand1 * operand2;
case '/':
return operand1 / operand2;
}
throw new IllegalArgumentException("Invalid operator: " + operator);
}
public static void main(String[] args) {
String[] tokens = { "3", "4", "2", "*", "1", "+", "/" };
double result = calculate(tokens);
System.out.println(result);
}
}
这个计算器可以读入一个由逆波兰表达式表示的数学表达式,例如:{ "3", "4", "2", "*", "1", "+", "/" },计算它的结果。运行结果为:2.3333333333333335。
阅读全文