0

This code is about evaluation of Postfix expression using stack.

Main class

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        Solution r = new Solution();
        System.out.println(r.evaluatePostFix(s));
    }
}

Solution class

public class Solution {
    public static int evaluatePostFix(String S) {
        Stack<Character> st = new Stack<>();
        int c1, c2;
        int op = 0;
        for (int i = 0; i < S.length(); i++) {
            char c = S.charAt(i);
            switch(c) {
                case '+':
                    c1 = (int) st.pop();
                    c2 = (int) st.pop();
                    op = c2 + c1;
                    st.push((char) op);
                    break;
                case '-':
                    c1 = (int) st.pop();
                    c2 = (int) st.pop();
                    op = c2 - c1;
                    st.push((char) op);
                    break;
                case '*':
                    c1 = (int) st.pop();
                    c2 = (int) st.pop();
                    op = c2 * c1;
                    st.push((char) op);
                    break;
                case '/':
                    c1 = (int) st.pop();
                    c2 = (int) st.pop();
                    op = c2 / c1;
                    st.push((char) op);
                    break;
                default:
                    st.push(c);
            }

            System.out.println(st);
        }

        return st.peek();
    }
}

What's going wrong? For input 345+*, I got:

[3]
[3, 4]
[3, 4, 5]
[3, i]
[ᓫ]
5355

but 27 is expected!

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 2
    [parsing - Java: parse int value from a char - Stack Overflow](https://stackoverflow.com/questions/4968323/java-parse-int-value-from-a-char) – user202729 Jan 27 '21 at 12:52
  • 1
    This is a *great* opportunity to start using a debugger to step through the code line by line and observe its behaviors and values. When you do this, which specific operation first produces an unexpected result? What were the exact values used? What was the result? What result was expected? Why? – David Jan 27 '21 at 12:53
  • @David Can't say that op didn't try. The other problem is that java prints a char value and an int value in an array the same way. – user202729 Jan 27 '21 at 12:54
  • (in retrospect op probably want double, if there's a division too.) – user202729 Jan 27 '21 at 12:55
  • 1
    Does this answer your question? [Java: parse int value from a char](https://stackoverflow.com/questions/4968323/java-parse-int-value-from-a-char) – larsaars Jan 27 '21 at 13:29
  • @user202729 If you don't mind, can you elaborate? – user14549997 Jan 28 '21 at 07:03
  • You need to convert it to integer value before doing arithmetic on it... – user202729 Jan 28 '21 at 10:40

0 Answers0