You are on page 1of 4

//SOUVIK & SOUMODIP

A program to find the value for a prefix expression.

import java.io.*;
import java.util.*;
public class prefix
{
public static void main()throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the prefix expression(followed by spaces
after each element)--------->");
String s=br.readLine();
System.out.println("The evaluated expression is "+process(s));
}
public static int X[]=new int[100];
public static String Dec[]={"0","1","2","3","4","5","6","7","8","9"};
public static int top;
public static int process(String str)
{
StringTokenizer ob=new StringTokenizer(str);
int n=ob.countTokens(),op1=0,op2=0;
String Db[]=new String[n];
top=-1;
for(int i=0,j=n-1;i<n;i++,j--)
Db[j]=ob.nextToken();
for(int i=0;i<n;i++)
{
if(checkDigit(Db[i])==true)
push(Integer.parseInt(Db[i]));
else
{
op2=pop();
op1=pop();
push(eval(Db[i],op1,op2));
}
}
return(pop());
}
public static int eval(String C,int A,int B)
{
int res=0;
if(C.equals("+")==true) { res=A+B;}
else if(C.equals("-")==true){ res=A-B;}
else if(C.equals("*")==true){ res=A*B;}
else if(C.equals("/")==true){ res=A/B;}
else if(C.equals("^")==true){res=(int)Math.pow(A,B);}
else
{
System.out.println("Invalid Operation");
System.exit(0);
}
return(res);
}
public static void push(int N)
{
if(top==99)
System.out.println("Stack Overflow");
else{
top++;
X[top]=N;
}
}
public static int pop()
{
if(top==-1)
{
System.out.println("Stack is empty");
System.exit(0);
}
return(X[top--]);
}
public static boolean checkDigit(String num)
{
String tmp;
boolean flag=true;
for(int i=0;i<num.length();i++)
{
tmp=""+num.charAt(i);
for(int j=0;j<Dec.length;j++)
{
if(tmp.equals(Dec[j])==true)
{
flag=true;
break;
}
else flag=false;
}
}
return(flag);
}
}
SAMPLE OUTPUT:

Enter the prefix expression(followed by spaces after each element)-------->


*/-5648
The evaluated expression is 32

You might also like