Skip to content

Instantly share code, notes, and snippets.

@nikhil-RGB
Created March 26, 2024 10:39
Show Gist options
  • Save nikhil-RGB/c02fbbacc31d4cfa8a8bfa60a4bf1c9c to your computer and use it in GitHub Desktop.
Save nikhil-RGB/c02fbbacc31d4cfa8a8bfa60a4bf1c9c to your computer and use it in GitHub Desktop.
Compiler Design Experiment 8, evaluation of a post fix expression
import java.util.*;
public class PostFix {
public static void main(String[] args) {
System.out.println("Input Postix Expression");
String expression="";
Scanner sc=new Scanner(System.in);
expression=sc.nextLine();
sc.close();
System.out.println("Output= "+compute(expression));
}
public static double compute(String input)
{
Stack<Double> stack=new Stack<>();
Scanner tokenizer=new Scanner(input);
while(tokenizer.hasNext())
{
if(tokenizer.hasNextDouble())
{
Double s=tokenizer.nextDouble();
stack.push(s);
}
else
{
//code to compute addition subt, div, multi
String op=tokenizer.next();
double num2=stack.pop();
double num1=stack.pop();
double result=perform(num1,num2,op);
stack.push(result);
}
}
return stack.pop();
}
public static double perform(double op1,double op2, String op)
{
switch(op)
{
case "+":
return op1+op2;
case "-":
return op1-op2;
case "*":
return op1*op2;
case "/":
return op1/op2;
default:
return 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment