In: Computer Science
In Java language
Write a static method called "evaluate" that takes a string as a parameter. The string will contain a postfix expression, consisting only of integer operands and the arithmetic operators +, -, *, and / (representing addition, subtraction, multiplication, and division respectively). All operations should be performed as integer operations. You may assume that the input string contains a properly-formed postfix expression. The method should return the integer that the expression evaluates to. The method MUST use a stack to perform the evaluation. Specifically, you should use the Stack class from the java.util package.
Also, in the same file, write a program that prompts the user to enter a postfix expression. Your program should evaluate the expression and output the result. Your program should call the "evaluate" method described above. Here are some examples:
Postfix expression: 1 2 + Result: 3 Postfix expression: 1 2 + 3 4 - * Result: -3 Postfix expression: 3 4 5 + + 1 - Result: 11
import java.util.Scanner; import java.util.Stack; public class PostfixExpressionSolver { // Method to evaluate value of a postfix expression static int evaluatePostfix(String exp) { //create a stack Stackstack = new Stack (); String tokens[] = exp.split("\\s+"); // Scan all characters one by one for (int i = 0; i < tokens.length; i++) { if (tokens[i].trim().length() == 0) continue; char c = tokens[i].trim().charAt(0); // If the scanned character is an operand (number here), // push it to the stack. if (Character.isDigit(c)) stack.push(c - '0'); // If the scanned character is an operator, pop two // elements from stack apply the operator else { int val1 = stack.pop(); int val2 = stack.pop(); switch (c) { case '+': stack.push(val2 + val1); break; case '-': stack.push(val2 - val1); break; case '/': stack.push(val2 / val1); break; case '*': stack.push(val2 * val1); break; } } } return stack.pop(); } public static void main(String[] args) { String expression; Scanner scanner = new Scanner(System.in); System.out.print("Postfix expression: "); expression = scanner.nextLine(); System.out.println("Result: " + evaluatePostfix(expression)); } }
===========================================================
If you are satisfied with the solution,
please rate the answer.
Thanks : )