Blogroll

This blog is created for education about engineering students.All the engineering students are get free downloadable books here. not only books and also different software also available here

5.c.Evaluates the Postfix expression


iii) Evaluates the postfix expression.
import java.io.*;
import java.util.*;
class StackDemo
{
static int index,pos;
int T;
float stk[];
StackDemo()
{
stk=new float[10];
T=-1;
index=0;
pos=0;
}
void push(float s)
{
if(T>=19)
{
System.out.println("Stack overflow");
System.exit(0);
}else{
T=T+1;
stk[T]=s;
}
}
float pop()
{
float num;
if(T==-1)
{
System.out.println("Stack is empty");
return(0);
}
else
{
num=stk[T];
T--;
}
return(num);
}
float ExpEval(char sfix[],float data[])
{
int j=0;
float op1,op2,fs;
char ch;
while(sfix[j]!='\0')
{
ch=sfix[j];
if(sfix[j]>='a'||sfix[j]>=
'A'&&sfix[j]<='z'||sfix[j]<='Z')
{
push(data[j]);
}
else
{
op2=pop();
op1=pop();
switch(ch)
{
case '+':push(op1+op2);
break;
case '-':push(op1-op2);
break;
case '*':push(op1*op2);
break;
case '/':push(op1/op2);
break;
case '%':push(op1%op2);
break;
}
}
j++;
}
fs=pop();
return(fs);
}
}
class EvalPostFix
{
public static void main(String args[])
{
String str;
char postfix[]=new char[25];
float number[]=new float[25];
int j=0;
try{
BufferedReader br=new
BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter a postfix expression:");
str=br.readLine();
str.getChars(0,str.length(),postfix,0);
while(postfix[j]!='\0')
{
if(postfix[j]>='a'||postfix[j]
>='A'&&postfix[j]<='z'||postfix[j]<='Z')
{
System.out.println("enter a number for%c:"+postfix[j]);
number[j]=Integer.parseInt(br.readLine());
}
j++;
}
}
catch(Exception e)
{
System.out.println("Exception \n Read:"+e);
}
StackDemo s1=new StackDemo();
System.out.println("The result is "+s1.ExpEval(postfix,number));
}
}

No comments:

Post a Comment

Total Pageviews