Double stack implementation of simple expression evaluation

Keywords: Java

Double stack implementation of simple expression evaluation

The evaluation of double stack implementation expression is a classic example of using stack, which uses one stack to store operators and another stack to store operands.
The arithmetic expression is composed of parentheses, operators and operands. The implementation process of double stack evaluation is as follows:
1. Pushing an operand into the operand stack
2. Pushing operators into the operator stack
3. Ignore left parenthesis
4. When the closing bracket is encountered, an operator will pop up, then the operands required by the operator will pop up, and the results of the operator and operands will be stored in the operands stack.
Here is the code that implements the evaluation of a simple expression that preserves parentheses (that is, does not omit them).

Code implementation:

import java.util.Scanner;

public class Evaluate {

    MyStack<String> ops = new MyStack<>();//Operator stack
    MyStack<Double> vals = new MyStack<>();//Operand stack

    public double doEvaluate(Scanner sca) {
        while (sca.hasNext()) {
            //Scan input cache
            String s = sca.next();
            if (s.equals("=")) {
                //"=" will jump out of the loop
                break;
            }
            if (s.equals("(")) {
                //If it's left parenthesis, do nothing
            }else if (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")) {
                System.out.println("Operator" + s + "Stack up");
                ops.push(s);
            }else if (s.equals(")")) {
                String op = ops.pop();
                double v = vals.pop();
                if (op.equals("+")) {
                    v = vals.pop() + v;
                }else if (op.equals("-")) {
                    v = vals.pop() - v;
                }else if (op.equals("*")) {
                    v = vals.pop() * v;
                }else if (op.equals("/")) {
                    v = vals.pop() / v;
                }
                vals.push(v);
                System.out.println("Operation result" + v + "Stack up");
            }else {
                vals.push(Double.parseDouble(s));
                System.out.println("Operands" + Double.parseDouble(s) + "Stack up");
            }
        }
        return vals.pop();
    }
}

Test:

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Evaluate eva = new Evaluate();

        System.out.println("Please enter an arithmetic expression separated by spaces. For example: (1).2 + 2.3 ) = ");
        Scanner s = new Scanner(System.in);
        double result = eva.doEvaluate(s);
        System.out.println("The final result is:" + result);
    }
}

Operation result:

Posted by tyr_82 on Mon, 30 Dec 2019 20:55:51 -0800