Java Program to Evaluate PostFix Expressions

Here is java program to evaluate post fix expression using stack.

package postfixeval;
import java.io.*;
class stack {
    int size;
    int item[];
    int top;
    public stack() {
        size = 100;
        item = new int[size];
        top = -1;
    }
    public void push(int ele) {
        if (top == (size - 1)) {
            System.out.println("Stack Overflow");
        } else {
            top++;
            item[top] = ele;
        }
    }
    public int pop() {
        if (top == -1) {
            System.out.println("No Elements");
            return (-1);
        } else {
            int x = item[top];
            top--;
            return (x);
        }
    }
    public int peek() {
        if (top == -1) {
            System.out.println("No Elements");
            return (-1);
        } else
            return (item[top]);
    }
    public void display() {
        System.out.println();
        if (top == -1) {
            System.out.println("No Elements");
        } else {
            System.out.println("Stack is");
            for (int i = 0; i <= top; i++)
                System.out.println(item[i]);
        }
    }
}
class evalpostfix {
    stack st = new stack();
    String postfix;
    public evalpostfix(String str) {
        postfix = str;
    }
    public boolean isOperand(char ch) {
        if (ch >= '0' && ch <= '9')
            return true;
        else
            return false;
    }
    public int eval() {
        char po[] = postfix.toCharArray();
        int i = 0, a, b;
        while (i < po.length) {
            if (isOperand(po[i]))
                st.push(po[i] - '0');
            else {
                a = st.pop();
                b = st.pop();
                switch (po[i]) {
                    case '+':
                        st.push(a + b);
                        break;
                    case '-':
                        st.push(b - a);
                        break;
                    case '*':
                        st.push(a * b);
                        break;
                    case '/':
                        st.push(b / a);
                        break;
                    case '%':
                        st.push(b % a);
                        break;
                }
            }
            i++;
        }
        return (st.pop());
    }
}
public class Postfixeval {
    public static void main(String[] args) throws IOException {
        BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
        String str;
        System.out.println("Enter postfix string");
        str = obj.readLine();
        evalpostfix epf = new evalpostfix(str);
        System.out.println("Result:" + epf.eval());
    }
}
/* Output
Enter postfix string
623+-382/+*
Result:7
 */

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.