比如,输入 (2+3)*5.
或者是 (2>3)&&(a<5) 这种逻辑表达式的?
------解决思路----------------------
基本上还是用后缀式计算,这里先上一个不带括号的,之后再上带括号的
List<Object> toSuffix(String s) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("+", 0);
map.put("-", 0);
map.put("*", 1);
map.put("/", 1);
List<Object> list = new ArrayList<Object>();
String[] number = s.split("[^\\d]");
String[] operator = s.split("\\d+");
Stack<String> stack = new Stack<String>();
for (int i = 0; i < number.length; i++) {
if (operator[i].length() > 0) {
while (!stack.isEmpty()
&& map.get(operator[i]) <= map.get(stack.peek())) {
list.add(stack.pop());
}
stack.push(operator[i]);
}
list.add(Double.parseDouble(number[i]));
}
while (!stack.isEmpty()) {
list.add(stack.pop());
}
return list;
}
double calculate(List<Object> list) {
Stack<Double> stack = new Stack<Double>();
for (Object obj : list) {
if (obj instanceof Double) {
stack.push((Double) obj);
} else {
double b = stack.pop();
double a = stack.pop();
if (obj.equals("+"))
stack.push(a + b);
if (obj.equals("-"))
stack.push(a - b);
if (obj.equals("*"))
stack.push(a * b);
if (obj.equals("/"))
stack.push(a / b);
}
}
return stack.pop();
}
连续调用两个方法可以得到结果,运算符和优先级在第一个方法的map里,可以自己定义