Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need to evaluate a function like this: 2 3 4 - * 5 /. Would this code work? If

ID: 3639939 • Letter: I

Question

I need to evaluate a function like this: 2 3 4 - * 5 /.

Would this code work? If not, can anyone help me to fix it?

public static float postfixEvaluate(String expr) {
        Stack<String> operator = new Stack<String>();
        char c;
        Stack<Integer> stack = new Stack<Integer>();
        for(int j = 0; j < expr.length(); j++){
            c = expr.charAt(j);
            if (c =='1' ||c == '2'||c == '3' ||c == '4'||c == '5'||c == '6' ||c =='7'||c =='8'||c =='9'){
                int num= Character.digit(c, 10);
                stack.push(num);
            } else if (expr.equals("+") || expr.equals("-") || expr.equals("*") || expr.equals("/")){
                operator.push(expr);}
                // operator (string)
                int num2 = stack.pop();
                int num1 = stack.pop();
                int result;
                if (operator.equals("+")) {
                    result = num1 + num2;
                } else if (operator.equals("-")) {
                    result = num1 - num2;
                } else if (operator.equals("*")) {
                    result = num1 * num2;
                } else { // if (operator.equals("/")) {
                    result = num1 / num2;
                }
                stack.push(result);
            }
       
        return stack.pop();
    }
}

Explanation / Answer

Modified Code:

public static float postfixEvaluate(String expr) {
Stack<Character> operator = new Stack<Character>();
char c;
Stack<Integer> stack = new Stack<Integer>();
for(int j = 0; j < expr.length(); j++){
c = expr.charAt(j);
if (c =='1' ||c == '2'||c == '3' ||c == '4'||c == '5'||c == '6' ||c =='7'||c =='8'||c =='9'){
int num= Character.digit(c, 10);
stack.push(num);
}

else if (c=='+' || c=='-' || c=='*'|| c=='/')

{
operator.push(c);
// operator (string)
int num2 = stack.pop();
int num1 = stack.pop();
int result;
if (operator.equals("+")) {
result = num1 + num2;
} else if (operator.equals("-")) {
result = num1 - num2;
} else if (operator.equals("*")) {
result = num1 * num2;
} else { // if (operator.equals("/")) {
result = num1 / num2;
}
stack.push(result);
}
}
return stack.pop();
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote