给出一个包含加减乘除的算式,能够给出计算结果。算式中可以包含整数、加减乘除和合理的成对出现的括号。
输入:(30+20)*20/(15-10)
输出:200
算式匹配(如果把正则表达式改成能匹配浮点数的式子,在下面的函数中也能计算含有浮点数的表达式)
protected static List<String> disassemble(String expression) {
List<String> list = new ArrayList<String>();
// 匹配数字及+-*/()
Pattern patn = Pattern.compile("\\s*(\\d+|[^\\.,&&[\\(-/]])\\s*");
Matcher mat = patn.matcher(expression);
while (mat.find())
list.add(mat.group(1));
return list;
}
具体算式计算函数
protected static Double compute(Iterator<String> ite) {
Deque<Double> numDeque = new LinkedList<Double>();
Deque<String> signDeque = new LinkedList<String>();
Deque<Double> tempNumDeque = new LinkedList<Double>();
Deque<String> tempSignDeque = new LinkedList<String>();
while (ite.hasNext()) {
String str = ite.next();
if(str.matches("\\d+")){
numDeque.addLast(new Double(str));
} else if (str.equals("+") || str.equals("-")) {
signDeque.addLast(str);
continue;
} else if (str.equals("*") || str.equals("/")) {
tempNumDeque.addLast(numDeque.pollLast());
tempSignDeque.addLast(str);
continue;
} else if(str.equals("(")) {
numDeque.addLast(compute(ite));
} else if (str.equals(")")) {
break;
}
//如果临时运算符队列中存在运算符号,则说明临时数字队列中存在一个参与运算的数字,
//则把刚才添加到队里中的数字出提取出来放入临时队列中,进行一次临时运算并把结果存在队列的末尾
if (tempSignDeque.size() > 0) {
tempNumDeque.addLast(numDeque.pollLast());
numDeque.addLast(tempCompute(tempNumDeque, tempSignDeque));
}
}
return tempCompute(numDeque, signDeque);
}
protected static double tempCompute(Deque<Double> numDeque, Deque<String> signDeque) {
while (!signDeque.isEmpty()) {
// 从队列的头部取得两个数,然后计算
double sum = 0;
double a = numDeque.pollFirst();
double b = numDeque.pollFirst();
switch (signDeque.pollFirst().charAt(0)) {
case '+':
sum = a + b;
break;
case '-':
sum = a - b;
break;
case '*':
sum = a * b;
break;
case '/':
sum = a / b;
}
numDeque.addFirst(sum);
}
return numDeque.pollFirst();
}
具体调用
public static double evaluate(String expression) {
// 算式匹配分解
List<String> list = disassemble(expression);
return compute(list.iterator());
}