[Algorithm – Java] Calculate the value of the expression suffix – Calculate value of the postfix Equation

The validity of a mathematical expression in infix form of conventional computers will be converted to the inverse Polish notation (suffixes) for the calculation is easy. You can review the algorithm converting from infix to postfix in my article. In this article, I will present the method for calculating the value of an expression prefix and suffix with Stack.

Loop through the token of the postfix expression from left to right:
– If the operand: push vào stack
– If the operator: pop two operands off the stack and their values ​​based on this operator. Push it back into the stack results.
Element left in the stack after the main loop is the result of the expression.

With the array of elements elementMath of expression suffix.

public String valueMath(String[] elementMath){
		Stack <String> S = new Stack<String>();
		InfixToPostfix  IFP = new InfixToPostfix();
		for (int i=0; i<elementMath.length; i++){
			char c = elementMath[i].charAt(0);
			if (!IFP.isOperator(c)) S.push(elementMath[i]);
			else{
				double num = 0f;
				double num1 = Float.parseFloat(S.pop());
				double num2 = Float.parseFloat(S.pop());
				switch (c) {
					case '+' : num = num2 + num1; break;
					case '-' : num = num2 - num1; break;
					case '*' : num = num2 * num1; break;
					case '/' : num = num2 / num1; break;
					default:
						break;
				}
				S.push(Double.toString(num));
			}
		}
		 return S.pop();
	}