package ex205.exp;
import java.util.Stack;
public class ArithmeticExpression {
private String expr;
public ArithmeticExpression(String expr) {
this.expr = expr;
}
public int getResult() {
Stack<Integer> operandStack = new Stack<>();
Stack<String> operatorStack = new Stack<>();
String[] tokens = expr.split("\\s+");
for (String token : tokens) {
if (isNumber(token)) {
operandStack.push(Integer.parseInt(token));
} else if (token.equals("(")) {
operatorStack.push(token);
} else if (token.equals(")")) {
while (!operatorStack.peek().equals("(")) {
performOperation(operandStack, operatorStack);
}
operatorStack.pop();
} else if (isOperator(token)) {
while (!operatorStack.isEmpty() && precedence(token) <= precedence(operatorStack.peek())) {
performOperation(operandStack, operatorStack);
}
operatorStack.push(token);
}
}
while (!operatorStack.isEmpty()) {
performOperation(operandStack, operatorStack);
}
return operandStack.pop();
}
private boolean isNumber(String token) {
try {
Integer.parseInt(token);
return true;
} catch (NumberFormatException e) {
return false;
}
}
private boolean isOperator(String token) {
return token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/");
}
private int precedence(String operator) {
if (operator.equals("+") || operator.equals("-")) {
return 1;
} else if (operator.equals("*") || operator.equals("/")) {
return 2;
} else {
return 0;
}
}
private void performOperation(Stack<Integer> operandStack, Stack<String> operatorStack) {
int num2 = operandStack.pop();
int num1 = operandStack.pop();
String operator = operatorStack.pop();
int result = 0;
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
}
operandStack.push(result);
}
}
package ex205;
import ex205.exp.ArithmeticExpression;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个符合整数算术四则运算表达式的字符串:(运算数和运算符号之间以空格隔开)");
String expression = scanner.nextLine();
ArithmeticExpression arithmeticExpression = new ArithmeticExpression(expression);
int result = arithmeticExpression.getResult();
System.out.println(result);
scanner.close();
}
}