数据结构课程设计表达式计算java完整代码
时间: 2023-10-14 20:12:48 浏览: 87
以下是基于栈的表达式计算Java代码:
```java
import java.util.Stack;
public class ExpressionCalculator {
// 判断是否为运算符
private static boolean isOperator(char ch) {
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
// 计算两个数的结果
private static double calculate(double a, double b, char operator) {
switch (operator) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
default:
return 0;
}
}
// 计算表达式的值
public static double evaluate(String expression) {
Stack<Double> operands = new Stack<>();
Stack<Character> operators = new Stack<>();
for (int i = 0; i < expression.length(); i++) {
char ch = expression.charAt(i);
if (Character.isDigit(ch)) { // 如果是数字
double num = ch - '0';
while (i + 1 < expression.length() && Character.isDigit(expression.charAt(i + 1))) {
num = num * 10 + expression.charAt(++i) - '0';
}
operands.push(num);
} else if (isOperator(ch)) { // 如果是运算符
while (!operators.isEmpty() && operators.peek() != '(' && (ch != '*' && ch != '/') || (ch == '*' || ch == '/') && (operators.peek() == '*' || operators.peek() == '/')) {
double b = operands.pop();
double a = operands.pop();
char operator = operators.pop();
operands.push(calculate(a, b, operator));
}
operators.push(ch);
} else if (ch == '(') { // 如果是左括号
operators.push(ch);
} else if (ch == ')') { // 如果是右括号
while (operators.peek() != '(') {
double b = operands.pop();
double a = operands.pop();
char operator = operators.pop();
operands.push(calculate(a, b, operator));
}
operators.pop();
}
}
while (!operators.isEmpty()) { // 处理剩余的运算符和操作数
double b = operands.pop();
double a = operands.pop();
char operator = operators.pop();
operands.push(calculate(a, b, operator));
}
return operands.pop();
}
public static void main(String[] args) {
String expression = "2*(3+5)/4-1";
double result = evaluate(expression);
System.out.println(expression + " = " + result);
}
}
```
该代码实现了基本的四则运算,包括加、减、乘、除和括号。其中使用两个栈分别存储操作数和运算符。在遍历表达式时,如果遇到数字则入栈操作数栈,如果遇到运算符则进行运算,将结果入栈操作数栈。最终得到的操作数栈中只剩下一个元素,即为表达式的值。
阅读全文