postfix exp
import java.util.*;
public class PostfixEvaluation{
int top,size=100;
int[] arr;
PostfixEvaluation(){
top=-1;
arr=new int[size];
}
public boolean isEmpty(){
if(top==-1)
return true;
else
return false;
}
public boolean isFull(){
if(top==size-1)
return true;
else
return false;
}
public void push(int ele){
if(isFull())
System.out.println("No operand can be inserted");
else{
top++;
arr[top]=ele;
}
}
public int pop(){
if(isEmpty())
return-1;
else{
int ele=arr[top];
top--;
return ele;
}
}
public boolean isOperator(char ch){
if(ch=='+' || ch=='-' || ch=='' || ch=='/')
return true;
else
return false;
}
public void evaluatePostfix(String exp){
int n =exp.length();
for(int i=0;i<n;i++){
if(isOperator(exp.charAt(i)))
{
int op1=pop();
int op2=pop();
switch(exp.charAt(i))
{
case'+':push(op2+op1);
break;
case'-':push(op2-op1);
break;
case'':push(op2*op1);
break;
case'/':push(op2/op1);
break;
}
}
else{
int op=exp.charAt(i)-'0';
push(op);
}
}
System.out.println(pop());
}
public static void main(String[] args){
String exp;
int ch;
Scanner sc=new Scanner(System.in);
PostfixEvaluation ob=new PostfixEvaluation();
System.out.print("Enter 1 to evaluate postfix expression\nEnter 2 to exit");
while(true){
System.out.print("\nEnter your option:");
ch=sc.nextInt();
switch(ch){
case 1:System.out.print("Enter the postfix expression:");
exp=sc.next();
ob.evaluatePostfix(exp);
break;
case 2:System.exit(1);
default:System.out.println("Enter your right option");
break;
}
}
}
}