1

I was solving a question where the task is to evaluate the postfix expression and find the final value.

this is my solution code

public static int evaluatePostFix(String S)
Stack<Integer> s = new Stack<>();
        
        int n = S.length();
        
        for(int i =0 ; i < n; i ++){
            char c = S.charAt(i);
            
            if(c >='0'&& c <= '9'){ // operand
                int temp = (int)(c -'0');
                
                s.push(temp);
            }else{ //operator
                
               int op1=  s.pop();
               int op2=  s.pop();
                
                if(c == '+'){
                    s.push(op2 + op1);
                    break;
                }
                if(c == '-'){
                    s.push(op2 - op1);
                    break;
                }
                if(c == '*'){
                    s.push(op2 * op1);
                    break;
                }
                if(c == '/'){
                    s.push(op2 / op1);
                    break;
                }
            
                
            }
        }
        
        return s.peek();

it doesn't give the correct output for if and else instead for switch statement given below it does

switch(c){
                    case '+':
                        s.push(op2 + op1);
                        break;
                    case '-':
                        s.push(op2 - op1);
                        break;
                    case '*':
                        s.push(op2 * op1);
                        break;    
                    case '/':
                        s.push(op2 / op1);
                        break;
                }

can someone explain it to me why is it happening

  • If your aim to continue the loop (without checking the other `if`-s which won't match anyway), you can use `continue;`. – tevemadar Mar 12 '23 at 11:57

0 Answers0