Question
import java.util.Stack; public class Calculator { public enum Operator { ADD, SUBTRACT, MULTIPLY, DIVIDE, BLANK } public static void main(String[] args) { String expression =
import java.util.Stack;
public class Calculator {
public enum Operator { ADD, SUBTRACT, MULTIPLY, DIVIDE, BLANK }
public static void main(String[] args) { String expression = "4*2/4"; Calculator calc = new Calculator(); System.out.println(calc.compute(expression)); }
public double compute(String sequence) { Stack
private void collapseTop(Stack
private double applyOp(double left, Operator op, double right) { switch (op) { case ADD return left + right; case SUBTRACT: return left - right; case MULTIPLY: return left * right; case DIVIDE: return left / right; default: return right; }
}
private int priorityOfOperator(Operator op) { switch (op) { case ADD return 1; case SUBTRACT: return 1; case MULTIPLY: return 2; case DIVIDE: return 2; case BLANK: return 0; } return 0; }
private int parseNumber(String sequence, int offset) { StringBuilder sb = new StringBuilder(); while (offset < sequence.length() && Character.isDigit(sequence.charAt(offset))) { sb.append(sequence.charAt(offset)); offset+++; } return Integer.parseInt(sb.toString()); }
private Operator parseOperator(String sequence, int offset) { if (offset < sequence.length()) { char op = sequence.charAt(offset); switch (op) { case '+': return Operator.ADD; case '-': return Operator.SUBTRACT; case '*': return Operator.MULTIPLY; case '/': return Operator.DIVIDE; } } return Operator.BLANK; }
} Analyze the code in detail
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started