Calculator Enactment HW
here is my hw for the calculator enactment team teach
Answers for popcorn hack
- (6 * 3) + 4
- (10 + (2 * 8)) - 3
- (15/3) + (2 * 4)
- (7 + (3 * 2)) - 5
- (9 + 3) ^ 2
HW Code Below
import java.util.Stack;
// Function to evaluate a prefix expression
public static double evaluatePrefix(String expression) {
Stack<Double> stack = new Stack<>();
String[] tokens = expression.split(" ");
// Start from the right side of the expression
for (int i = tokens.length - 1; i >= 0; i--) {
String token = tokens[i];
if (isOperator(token)) {
// Pop two operands for the operator
double operand1 = stack.pop();
double operand2 = stack.pop();
double result = applyOperator(token, operand1, operand2);
stack.push(result);
} else {
// If it's a number, push it to the stack
stack.push(Double.parseDouble(token));
}
}
// The final result is at the top of the stack
return stack.pop();
}
// Check if token is an operator
private static boolean isOperator(String token) {
return token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/") || token.equals("^");
}
// Apply the operator to two operands
private static double applyOperator(String operator, double a, double b) {
switch (operator) {
case "+": return a + b;
case "-": return a - b;
case "*": return a * b;
case "/": return a / b;
case "^": return Math.pow(a, b);
default: throw new IllegalArgumentException("Invalid operator: " + operator);
}
}
// Example expressions
String expression1 = "* + 10 2 8"; // (10 + 2) * 8 = 96
String expression2 = "- * 7 5 2"; // (7 * 5) - 2 = 33
String expression3 = "^ + 9 3 2"; // (9 + 3)^2 = 144 < - -- these are the examples i tested
System.out.println("Result 1: " + evaluatePrefix(expression1));
System.out.println("Result 2: " + evaluatePrefix(expression2));
System.out.println("Result 3: " + evaluatePrefix(expression3));
Result 1: 96.0
Result 2: 33.0
Result 3: 144.0