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