postfix evaluation calculated result is wrong

69 views Asked by At

I'm trying to implement postfix evaluation using stack, but the result after calculation is not correct, I cannot figure out which part makes the calculation wrong, thanks a lot.

import java.util.Stack;

public class PostFixEvaluate {
    public static float calculate(Float operand_1,char operator,Float operand_2 ){
        switch(operator){
            case '+':
                return operand_2 + operand_1;

            case '-':
                return operand_2 - operand_1;

            case '*':
                return operand_2 * operand_1;

            case '/':
                return operand_2 / operand_1;
        }

        return 0;
    }   //end calculate()

    public static float postFixEvaluation(String expr){
        Stack<Float> stack = new Stack<>();
        int index = 0;

        while(index < expr.length()){
            char token = expr.charAt(index);
            boolean x = isOperand(token);

            if(x == true){     //operand
                float operandIn = (float)token;
                stack.push(operandIn);
            }
            else{           //operator
                float a = stack.pop();   //operand_1
                float b = stack.pop();   //operand_2
                char w = token;         //operator
                stack.push(calculate(a, w, b));
            }
            index += 1;
        }   //end while

        float result = stack.pop();
        return result;
     }  //postFixEvaluation()

    /*Operand or operator? operator return 1, operand return 2*/
     public static boolean isOperand(char c){
        switch(c){
            case '+':
            case '-':
            case '*':
            case '/':
                return false;   //an operator
            default:
                return true;   //an operand
        }   //end switch()
    }  //end isOperand()
}

After entering the postfix "312*+456*+97-/+", the result is 3958.0, which is expected to be 22.0, That is much more than wrong but I still cannot figure out why the result is 3958.0.

1

There are 1 answers

2
Federico klez Culloca On

char token = expr.charAt(index); returns '3' on the first iteration, but that's a char representing the character '3' (i.e. 51), not the number 3.

To use the number instead of the character representing that number you can push it into the stack by subtracting '0' from it, like this:

stack.push(operandIn - '0');