Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

switch-statement gives correct output but if-else doesn't

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

The issue with your code is that you are using "break" statements after each operation inside the if statements. The "break" statement immediately terminates the loop, and therefore your code is only performing the first operation encountered in the postfix expression.

To fix your code, simply remove the "break" statements in the if statements and your original implementation should work correctly.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading