In: Computer Science
JAVA - PLEASE COMMENT CODE - THANK YOU:
Implement a program that can input an expression in postfix notation and output its value.
import java.util.*;
public class PostfixToValue
{
// Method to evaluate value of a postfix expression
static int evaluatePostfix(String exp)
{
//create a stack
Stack<Integer> stack = new Stack<>();
// Scan all the characters one by one
for(int i = 0; i < exp.length(); i++) //Iterate over each and check
{
char op = exp.charAt(i);
if(op == ' ')
continue;
// If the scanned character is an operand
// (number here),extract the number
// Push it to the stack.
else if(Character.isDigit(op))
{
int n = 0;
//extract the characters and store it in num
while(Character.isDigit(op))
{
n = n*10 + (int)(op-'0');
i++;
op = exp.charAt(i);
}
i--;
//push the number in stack
stack.push(n);
}
// 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(op)
{
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)
{
System.out.print("Enter postfix expression: ");
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
String postexp=sc.nextLine();
System.out.print(evaluatePostfix(postexp));//takes the input and evaluates the post fix expression.
}
}
This is how the output appears.
It takes the postfix expression given by user and evaluates it to a
value and prints that value.