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
>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.