if (false == isNumber(ch)) {
return false;
}
}
return true;
}
/**
* 检查一个字符是否为数字
* @param ch
* @return
*/
private boolean isNumber(char ch) {
if (ch >= '0' && ch <= '9') {
return true;
}
return false;
}
/**
* 查表得到op1和op2的优先级
* @param op1 运算符1
* @param op2 运算符2
* @return ">", "<" 或 "="
*/
public String priority(String op1, String op2) {
return priorityMap.get(op1).get(op2);
}
/**
* 构造方法,初始化优先级表
*/
public EvaluateExpression() {
// initialize stack
optStack.push("#");
// initialize priority table
// +
Map<String, String> subMap = new HashMap<String, String>();
subMap.put("+", ">");
subMap.put("-", ">");
subMap.put("*", "<");
subMap.put("/", "<");
subMap.put("(", "<");
subMap.put(")", ">");
subMap.put("#", ">");
priorityMap.put("+", subMap);
// -
subMap = new HashMap<String, String>();
subMap.put("+", ">");
subMap.put("-", ">");
subMap.put("*", "<");
subMap.put("/", "<");
subMap.put("(", "<");
subMap.put(")", ">");
subMap.put("#", ">");
priorityMap.put("-", subMap);
// *
subMap = new HashMap<String, String>();
subMap.put("+", ">");
subMap.put("-", ">");
subMap.put("*", ">");
subMap.put("/", ">");
subMap.put("(", "<");
subMap.put(")", ">");
subMap.put("#", ">");
priorityMap.put("*", subMap);
// /
subMap = new HashMap<String, String>();
subMap.put("+", ">");
subMap.put("-", ">");
subMap.put("*", ">");
subMap.put("/", ">");
subMap.put("(", "<");
subMap.put(")", ">");
subMap.put("#", ">");
priorityMap.put("/", subMap);
// (
subMap = new HashMap<String, String>();
subMap.put("+", "<");
subMap.put("-", "<");
subMap.put("*", "<");
subMap.put("/", "<");
subMap.put("(", "<");
subMap.put(")", "=");
//subMap.put("#", ">");
priorityMap.put("(", subMap);
// )
subMap = new HashMap<String, String>();
subMap.put("+", ">");
subMap.put("-", ">");
subMap.put("*", ">");
subMap.put("/", ">");
//subMap.put("(", "<");
subMap.put(")", ">");
subMap.put("#", ">");
priorityMap.put(")", subMap);
// #
subMap = new HashMap<String, String>();
subMap.put("+", "<");
subMap.put("-", "<");
subMap.put("*", "<");
subMap.put("/", "<");
subMap.put("(", "<");
//subMap.put(")", ">");
subMap.put("#", "=");
priorityMap.put("#", subMap);
}
}
程序测试:
String exp = "4 * ( 10 + 2 ) + 1 #";
EvaluateExpression ee = new EvaluateExpression();
out.println(ee.calcualte(exp));
运行结果为 49。
Java 9 的新特性发布
Java编程思想(第4版) 中文清晰PDF完整版