在 Java 中计算数学表达式

Zeeshan Afridi 2023年10月12日

Stack 有两种标准方法，`pop()``push()`，用于从堆栈中放入和获取操作数或运算符。`pop()` 方法删除表达式的顶部元素，而 `push()` 方法将一个元素放在堆栈顶部。

在 Java 中计算数学表达式

``````package evaluateexpression;

import java.util.Scanner;
import java.util.Stack;

public class EvaluateExpression {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

// Creating stacks for operators and operands
Stack<Integer> operator = new Stack();
Stack<Double> value = new Stack();

// Let's create some temparory stacks for operands and operators
Stack<Integer> tmpOp = new Stack();
Stack<Double> tmpVal = new Stack();

// Enter an arthematic expression
System.out.println("Enter expression");
String input = scan.next();
System.out.println(
"The type of the expression is " + ((Object) input).getClass().getSimpleName());
input = "0" + input;
input = input.replaceAll("-", "+-");

// In the respective stacks store the operators and operands
String temp = "";
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (ch == '-')
temp = "-" + temp;
else if (ch != '+' && ch != '*' && ch != '/')
temp = temp + ch;
else {
value.push(Double.parseDouble(temp));
operator.push((int) ch);
temp = "";
}
}
value.push(Double.parseDouble(temp));

// Create a character array for the operator precedence

char operators[] = {'/', '*', '+'};

/* Evaluation of expression */
for (int i = 0; i < 3; i++) {
boolean it = false;
while (!operator.isEmpty()) {
int optr = operator.pop();
double v1 = value.pop();
double v2 = value.pop();

if (optr == operators[i]) {
// if operator matches evaluate and store it in the temporary stack
if (i == 0) {
tmpVal.push(v2 / v1);
it = true;
break;
} else if (i == 1) {
tmpVal.push(v2 * v1);
it = true;
break;
} else if (i == 2) {
tmpVal.push(v2 + v1);
it = true;
break;
}
} else {
tmpVal.push(v1);
value.push(v2);
tmpOp.push(optr);
}
}
// pop all the elements from temporary stacks to main stacks
while (!tmpVal.isEmpty()) value.push(tmpVal.pop());
while (!tmpOp.isEmpty()) operator.push(tmpOp.pop());
// Iterate again for the same operator
if (it)
i--;
}
System.out.println("\nResult = " + value.pop());
}
}
``````

``````Enter expression
2+7*5-3/2
The type of the expression is String

Result = 35.5
``````

Zeeshan is a detail oriented software engineer that helps companies and individuals make their lives and easier with software solutions.