Thursday, April 14, 2011

Java implementation of Postfix Evaluation


import java.util.Scanner;

class PostFixEval
{
    boolean isDigit(char ch)
    {
        if(ch>='0'&& ch<='9')
            return true;
        else
            return false;
    }

    void Eval(String expr)
    {
        int position;
        char c;
        double num1,num2,value;
        Stack_Num s=new Stack_Num();
        s.top=-1;
        for(position=0;position<expr.length(); position++)
        {

            c=expr.charAt(position);
            if(isDigit(c))
                s.Push((double)(c -'0'));
            else
            {
                num2=s.Pop();
                num1=s.Pop();
                value=Calc(c,num1,num2);
                s.Push(value);
            }
        }
        value=s.Pop();
        if(!s.isEmpty())
            System.out.println("Expression is wrong!!!!!!!!!!!");
        else
            System.out.println("Result of postfix expression is "+value);
    }

    double Calc(char ch,double num1,double num2)
    {
        switch(ch)
        {
            case '+':return(num1+num2);
            case '-':return(num1-num2);
            case '*':return(num1*num2);
            case '/':return(num1/num2);
            case '^':return(Math.pow(num1,num2));
            default:System.out.println("\nillegal operator found");
        }
        return(0);
    }

    public static void main(String args[])
    {
        String expr=new String();
        Scanner in = new Scanner(System.in);
        PostFixEval eqn=new PostFixEval();
        System.out.println("Use digits(0-9)and operators(+,-,*,/,$)");
        System.out.println("Enter an expression in postfix form :");
        expr=in.nextLine();
        System.out.println("Original postfix expression is " + expr);
        eqn.Eval(expr);
    }
}

No comments:

Post a Comment