I have a problem i can’t find the wrong in this function it sometimes do well with some inputs but sometimes no for examle this Input “6 2 / 3 – 4 2 * +” can any one help.
public static double Evaluating_postfix_expressions(String postfix) throws Exception{
StringTokenizer st = new StringTokenizer(postfix);
int numOF_tokens = st.countTokens();
for (int i = 1; i <= numOF_tokens; i++) {
Object term = st.nextToken();
try { // if it is an operand there is no problem
float x = Float.parseFloat((String)term);
stack.push(x);
} catch (Exception e) { // it is an operator
float v1 = (float) stack.pop();
float v2 = (float) stack.pop();
switch ((String) term) {
case "+":
stack.push(v2 + v1);
break;
case "-":
stack.push(v2 - v1);
break;
case "*":
stack.push(v2 * v1);
break;
case "/":
stack.push(v2 / v1);
break;
}
}
}
return (float) stack.pop();
}
Note that you’ve given an incorrect operator as input:
Note the difference with a version hand-typed right here:
You’ve used a dash instead of a hyphen — or the other way around:
This is part of the problem with a catch-all exception that doesn’t report any problems. You should modify your
switchto report invalid operators, which would have made catching this one significantly easier. (I just happened to think that it looked funny.)