[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(); }
Looks like you have not yet reviewed the case with open sign, closing parenthesis.
Then, Order will perform other calculations.
When expression was đk defined suffixes are not there anymore you have a couple.
The main function writes stars vay76
Star writes that the main function you.
🙂 chuyển từ Infix sang PostFix được nhưng chạy cái tính ra kết quả bị lỗi anh ơi, để ValueMatch dưới cùng trong main sau khi đã chuyển ra được Postfix nhưng vẫn bị lỗi. ANh có thể check code lại giúp không anh
chắc cú pháp biểu thức của bạn sai. mình test chạy đúng mà.
Trong hàm valueMath bạn chạy i từ 1 là ra đúng nhá, mình cũng bị chỗ ni, không rõ sao elementMath phần tử đầu là rỗng nên sẽ sai.??? Fix run correctly but do not understand the reason, looking for the reason here you.
show me the main function with b