Postfix evaluation for multidigit numbers

chettyharish picture chettyharish · Mar 10, 2014 · Viewed 7.2k times · Source

I as programming a postfix evaluator, and I was able to do it correctly for single digit number. Now I need an idea of how to do it for multiple digit number, as my current program evaluates a two digit number as different numbers.

Here's the code :

public class PostfixEvaluation {

    public static void main(String[] args) {
        String postfix = "23+79*-";

        Stack stack = new Stack();

        for (int i = 0; i < postfix.length(); i++) {
            if (postfix.charAt(i) == '+') {
                int v1 = stack.pop();
                int v2 = stack.pop();
                stack.push(v2 + v1);
            } else if (postfix.charAt(i) == '-') {
                int v1 = stack.pop();
                int v2 = stack.pop();
                stack.push(v2 - v1);
            } else if (postfix.charAt(i) == '*') {
                int v1 = stack.pop();
                int v2 = stack.pop();
                stack.push(v2 * v1);
            } else if (postfix.charAt(i) == '/') {
                int v1 = stack.pop();
                int v2 = stack.pop();
                stack.push(v2 / v1);
            } else if (postfix.charAt(i) == '^') {
                int v1 = stack.pop();
                int v2 = stack.pop();
                stack.push((int) Math.pow(v2, v1));
            } else {
                stack.push((int) postfix.charAt(i) - 48);
            }
        }
        System.out.println(stack.pop());
    }

}

Answer

Sufian Latif picture Sufian Latif · Mar 10, 2014

To be able to identify multi-digit numbers, there must be a separator symbol between two numbers.

For example, you can use space as the separator symbol. All the tokens in postfix will be space separated. Your example would become "2 3 + 7 9 * -". You should read one token at a time, not one character.