Popcorn Hack

  1. 6*3+4
  2. 10+2*8-3
  3. 15/3+4*2
  4. 7+3*2-5
  5. (9+3)^2

Homework

import java.util.Stack;


public static double calculatePrefix(String expression) {
    String[] tokens = expression.split(" ");
    Stack<Double> stack = new Stack<>();

    for (int i = tokens.length - 1; i >= 0; i--) {
        String token = tokens[i];

        if (isNumeric(token)) {
            stack.push(Double.parseDouble(token));
        } else {
            double operand2 = stack.pop();
            double operand1 = stack.pop();
            double result = performOperation(token, operand1, operand2);
            stack.push(result);
        }
    }
    return stack.pop();
}

private static double performOperation(String operator, double operand1, double operand2) {
    switch (operator) {
        case "+":
            return operand1 + operand2;
        case "-":
            return operand1 - operand2;
        case "*":
            return operand1 * operand2;
        case "/":
            return operand1 / operand2;
        default:
            return 0;
    }
}

private static boolean isNumeric(String str) {
    try {
        Double.parseDouble(str);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

double result1 = calculatePrefix("* 3 5");
double result2 = calculatePrefix("* 2 - 7 5");

System.out.println(result1);
System.out.println(result2);
    



15.0
-4.0