在 Java 中计算数学表达式

Zeeshan Afridi 2023年10月12日
在 Java 中计算数学表达式

使用堆栈评估数学表达式是最常见和有用的选项之一。

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

在 Java 中计算数学表达式

这是一个用 Java 计算数学表达式的示例。此代码遵循正确的 DMAS 规则,具有以下优先级:除法、乘法、加法和减法。

你可以给它任何数学表达式作为输入,但要确保表达式仅包含以下四种运算(加法、乘法、除法和减法)。

示例代码:

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

正如你在上述代码的输出中看到的,表达式 2+7*5-3/2 作为输入给出。程序计算结果为 35.5

它首先划分 3/2 = 1.5,因为在 DMAS 规则中,划分具有最高优先级。然后乘法部分计算为 7*5 = 35

接下来,我们有 2+35 = 37 的加法,表达式的最后一部分是减法,即 37 -1.5 = 35.5

作者: Zeeshan Afridi
Zeeshan Afridi avatar Zeeshan Afridi avatar

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

LinkedIn

相关文章 - Java Math