// 中缀转后缀
tokens = toRpn(tokens);
// 计算结果
System.out.println(calcRpn(tokens));
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 将输入串转换为操作符串
*
* @param sExpres
* @return
*/
public static List<String> lex(String sExpres) {
List<String> tokens = new ArrayList<String>();
// 将表达式分割成符号序列
String sRegExp = "(((?<=^|\\(|\\+|-|\\*|/|%)(\\+|-))?\\d+(\\.\\d+)?)"
+ "|\\(|\\)|\\*|/|\\+|-";
Pattern p = Pattern.compile(sRegExp);
Matcher m = p.matcher(sExpres.replaceAll("\\s+", ""));
while (m.find()) {
tokens.add(m.group());
}
tokens.add("#");
return tokens;
}
/**
* 将中缀表单时转化为后缀表达式
*
* @param tokens
* @return
*/
public static List<String> toRpn(List<String> tokens) throws Exception {
List<String> rpnList = new ArrayList<String>();
Stack<String> optrStack = new Stack<String>();
optrStack.add("^");
for (String token : tokens) {
if (token.matches("^(\\+|-)?\\d+(\\.\\d+)?$")) {
rpnList.add(token);
} else {
outputOptr(token, optrStack, rpnList);
}
}
if (!optrStack.isEmpty() && optrStack.lastElement().equals("#")) {
return rpnList;
} else {
throw new Exception("后缀表达式转化错误!");
}
}
/**
* 计算后缀表达式的值
*
* @param rpnTokens
* @return
* @throws Exception
*/
public static double calcRpn(List<String> rpnTokens) throws Exception {
NumberFormat nf = NumberFormat.getInstance();
Stack<Double> numStack = new Stack<Double>();
for (String token : rpnTokens) {
if (token.matches("^(\\+|-)?\\d+(.\\d+)?$")) {
token = token.indexOf('+') == 0 ? token.substring(1) : token;