In: Computer Science
Write in Java
Postfix notation is a way of writing expressions without using parentheses. For example, the expression (1 + 2) * 3 would be written as 1 2 + 3 *. A postfix expression is evaluated using a stack. Scan a postfix expression from left to right. A variable or constant is pushed into the stack. When an operator is encountered, apply the operator with the top two operands in the stack and replace the two operands with the result.. Write a program to evaluate postfix expressions. Pass the expression as a command-line argument in one string.
Command line argument:
“1 2 + 3 *”
Correct output (3 points):
9
import java.util.Scanner;
import java.util.Stack;
public class PostFixEval
{
// Method to evaluate value of a postfix expression
public static int evaluateExpression(String exp)
{
//create a stack
Stack<Integer> expressionStack=new Stack<>();
// iterate all characters one by one
for(int i=0;i<exp.length();i++)
{
char c=exp.charAt(i);
if(c==' ')
continue;
// If the scanned character is an operand (number here),
// push it to the stack.
if(Character.isDigit(c))
expressionStack.push(c - '0');
// If the scanned character is an operator, pop top 2 and apply
operation
else
{
int num1 = expressionStack.pop();
int num2 = expressionStack.pop();
switch(c)
{
case '+':
expressionStack.push(num2+num1);
break;
case '-':
expressionStack.push(num2- num1);
break;
case '/':
expressionStack.push(num2/num1);
break;
case '*':
expressionStack.push(num2*num1);
break;
}
}
}
return expressionStack.pop();
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter expression");
String exp=sc.nextLine();
System.out.println("postfix evaluation:
"+evaluateExpression(exp));
}
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me