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
code:
import java.util.*;
class PostfixEvaluator
{
static int evaluate(String exp)
{
Stack
for(int i=0;i
char
c=exp.charAt(i);
if(Character.isDigit(c))// If the scanned character is an operand
(number here), push it to the stack.
s.push(c -
'0');
else
{
int v1 = s.pop();
int v2 = s.pop();
// If the scanned character is an operator, pop
two elements from stack apply the operator
if(c=='+')
s.push(v2+v1);
if(c=='-')
s.push(v2- v1);
if(c=='/')
s.push(v2/v1);
if(c=='*')
s.push(v2*v1);
}
}
return s.pop();
//returning the result
}
public static void main(String[] args) //main
method
{
String exp;
Scanner sc= new
Scanner(System.in);//scanner class to read the input
System.out.print("Postfix
expression: ");
exp=sc.next();
System.out.println("Result:
"+evaluate(exp));
}
}
output: