Infix To PostFix Stack
Infix To PostFix Stack
Conversion and
Evaluator CODES
-Eivuj Papas
/**
* StackTest.java
*NOTE: I used Stack using char int Array.
* @author ME – [email protected]
* @version 1.00 2010/8/4
*/
import java.io.*;
import java.util.*;
try{
input=dataIn.readLine();
}catch(IOException w){ System.out.println("Error"+w);}
input=input+")";
Stack stack=new Stack(input.length());
stack.push('(');
String post=stack.convert(input);
StringTokenizer output=new StringTokenizer(post);
System.out.println("\npostfix expression:");
while(output.hasMoreTokens())
{
System.out.print(output.nextToken()+" ");
}
int answer=evaluate.produce(post);
System.out.println("\nResult: ");
System.out.println(answer);
System.exit(0);
}
/**
* Stack.java
*NOTE: I used Stack using char int Array.
* @author ME – [email protected]
* @version 1.00 2010/8/4
*/
import java.io.*;
import java.util.*;
top++;
values[top] = data;
}
}
return retVal;
}
if(!isEmpty()) {
retVal=values[temp];
temp--;
}
return retVal;
else if(it=='/')
return 5;
else if(it=='%')
return 4;
else if(it=='+')
return3;
else if(it=='-')
return2;
else
return1;
}
while(i<in_put.length())
{
c=in_put.charAt(i);
if(Character.isDigit(c))
postfix.append(c).append(" ");
if(c=='(')
push('(');
if(c=='*'||c=='/'||c=='%'||c=='+'||c=='-')
{
char v=stackTop();
if(v=='*'||v=='/'||v=='%'||v=='+'||v=='-')
{
if(precedence(v)>=precedence(c))
{
{
postfix.append(pop()).append(" ").toString();
}
}
}
push(c);
}
if(c==')')
{ char st=stackTop();
while(st!='('&&!isEmpty())
{
postfix.append(pop()).append(" ").toString();
st=stackTop();
}
pop();
}
i++;
}
return postfix.toString();
/**
* Evaluator_Postfix.java
*NOTE: I used Stack using char int Array.
* @author ME – [email protected]
* @version 1.00 2010/8/4
*/
import java.io.*;
import java.util.*;
top++;
values[top] = data;
}
}
return retVal;
}
post_fix=post_fix+"\0";
int i=0;
int ans;
int x,y;
while(i<post_fix.length())
{
char c=post_fix.charAt(i);
if(Character.isDigit(c))
{
int l=(c-'0');
push(l);
if(c=='*'||c=='/'||c=='%'||c=='+'||c=='-')
{
x=pop();
y=pop();
//calculating
if(c=='*'){
ans=x*y;
push(ans);
}
if (c=='/'){
if(x<y)
{
ans=y/x;
push(ans);
}
else{
ans=x/y;
push(ans);
}
}
if (c=='%'){
ans=x%y;
push(ans);
}
if(c=='+'){
ans=x+y;
push(ans);
}
if(c=='-'){
if(x<y)
{
ans=y-x;
push(ans);
}
else{
ans=x-y;
push(ans);
}
}
if(c=='\0')
{
while(!isEmpty()){
valEx=pop();
}
}
i++;
}
return valEx;
}
Don't forget to say Thank You... You may visit my facebook account and here's my email add:
[email protected]. If Error occurs just debug it and hopefully understand the algorithm. BYE
--THE END--