Untitled
unknown
java
2 years ago
2.3 kB
4
Indexable
public static double evaluate(String expression) { Stack<Double> stack = new Stack<>(); Stack<Character> operatorStack = new Stack<>(); for (int i = 0; i < expression.length(); i++) { char c = expression.charAt(i); if (Character.isDigit(c) || c == '.') { StringBuilder sb = new StringBuilder(); sb.append(c); while (i + 1 < expression.length() && (Character.isDigit(expression.charAt(i + 1)) || expression.charAt(i + 1) == '.')) { sb.append(expression.charAt(i + 1)); i++; } stack.push(Double.parseDouble(sb.toString())); } else if (c == '+' || c == '-' || c == '*' || c == '/') { while (!operatorStack.isEmpty() && precedence(c) <= precedence(operatorStack.peek())) { double secondOperand = stack.pop(); double firstOperand = stack.pop(); char operator = operatorStack.pop(); stack.push(applyOperator(firstOperand, secondOperand, operator)); } operatorStack.push(c); } } while (!operatorStack.isEmpty()) { double secondOperand = stack.pop(); double firstOperand = stack.pop(); char operator = operatorStack.pop(); stack.push(applyOperator(firstOperand, secondOperand, operator)); } return stack.pop(); } private static int precedence(char operator) { if (operator == '+' || operator == '-') { return 1; } else if (operator == '*' || operator == '/') { return 2; } else { return -1; } } private static double applyOperator(double firstOperand, double secondOperand, char operator) { if (operator == '+') { return firstOperand + secondOperand; } else if (operator == '-') { return firstOperand - secondOperand; } else if (operator == '*') { return firstOperand * secondOperand; } else { return firstOperand / secondOperand; } }
Editor is loading...