Question:
You are give a piece of mathematical expression, e.g., 3 * 4 + 5, return the value of that expression.
public class EvaluateDeluxe {
// result of applying binary operator op to two operands val1 and val2
public static double eval(String op, double val1, double val2) {
if (op.equals("+")) return val1 + val2;
if (op.equals("-")) return val1 - val2;
if (op.equals("/")) return val1 / val2;
if (op.equals("*")) return val1 * val2;
throw new RuntimeException("Invalid operator");
}
public HashMap<String, Integer> priorityInfo(){
// precedence order of operators
HashMap<String, Integer> precedence = new HashMap<String, Integer>();
precedence.put("(", 0); // for convenience with algorithm
precedence.put(")", 0);
precedence.put("+", 1); // + and - have lower precedence than * and /
precedence.put("-", 1);
precedence.put("*", 2);
precedence.put("/", 2);
return precedence;
}
public double calculate(String[] stdIn, HashMap<String, Integer> precedence){
Stack<String> ops = new Stack<String>();
Stack<Double> vals = new Stack<Double>();
for (int i = 0; i < stdIn.length; i++) {
String s = stdIn[i];
// token is a value
if (!precedence.containsKey(s)) {
vals.push(Double.parseDouble(s));
continue;
}
// token is an operator
while (true) {
// the last condition ensures that the operator with higher precedence is evaluated first
if (ops.isEmpty() || s.equals("(") || (precedence.get(s) > precedence.get(ops.peek()))) {
ops.push(s);
break;
}
// evaluate expression
String op = ops.pop();
// but ignore left parentheses
if (op.equals("(")) {
assert s.equals(")");
break;
}
// evaluate operator and two operands and push result onto value stack
else {
double val2 = vals.pop();
double val1 = vals.pop();
vals.push(eval(op, val1, val2));
}
}
}
// finished parsing string - evaluate operator and operands remaining on two stacks
while (!ops.isEmpty()) {
String op = ops.pop();
double val2 = vals.pop();
double val1 = vals.pop();
vals.push(eval(op, val1, val2));
}
return vals.pop();
}
}The code is from:
http://algs4.cs.princeton.edu/13stacks/EvaluateDeluxe.java.html
本文介绍了一个名为EvaluateDeluxe的Java类,用于解析并计算数学表达式的值。该类通过使用栈来处理运算符和操作数,并遵循运算符的优先级规则。它支持加、减、乘、除四种基本运算。
1468

被折叠的 条评论
为什么被折叠?



