java算数表达式求值
时间: 2023-10-14 17:12:38 浏览: 84
Java中可以通过栈来实现算数表达式的求值。
具体步骤如下:
1. 创建两个栈,一个用来存储数字,一个用来存储操作符。
2. 将算数表达式转换为后缀表达式。
3. 遍历后缀表达式,如果是数字,则将其入数字栈,如果是操作符,则从数字栈中弹出两个数字进行计算,并将结果压入数字栈。
4. 最终数字栈中的唯一元素即为表达式的值。
下面是一个简单的示例代码:
```
import java.util.Stack;
public class ArithmeticExpressionEvaluation {
public static int evaluate(String expression) {
Stack<Integer> numbers = new Stack<>();
Stack<Character> operators = new Stack<>();
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
if (Character.isDigit(c)) {
int num = 0;
while (Character.isDigit(c)) {
num = num * 10 + (c - '0');
i++;
c = expression.charAt(i);
}
i--;
numbers.push(num);
} else if (c == '(') {
operators.push(c);
} else if (c == ')') {
while (operators.peek() != '(') {
int num2 = numbers.pop();
int num1 = numbers.pop();
char op = operators.pop();
int result = calculate(num1, num2, op);
numbers.push(result);
}
operators.pop();
} else if (isOperator(c)) {
while (!operators.isEmpty() && precedence(operators.peek()) >= precedence(c)) {
int num2 = numbers.pop();
int num1 = numbers.pop();
char op = operators.pop();
int result = calculate(num1, num2, op);
numbers.push(result);
}
operators.push(c);
}
}
while (!operators.isEmpty()) {
int num2 = numbers.pop();
int num1 = numbers.pop();
char op = operators.pop();
int result = calculate(num1, num2, op);
numbers.push(result);
}
return numbers.pop();
}
private static int calculate(int num1, int num2, char op) {
switch (op) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
default:
return 0;
}
}
private static boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
private static int precedence(char op) {
if (op == '*' || op == '/') {
return 2;
} else if (op == '+' || op == '-') {
return 1;
} else {
return 0;
}
}
public static void main(String[] args) {
String expression = "5 + ((1 + 2) * 4) - 3";
int result = evaluate(expression);
System.out.println(result); // Output: 14
}
}
```
阅读全文