假如我有字符串“(5+6)*7+9/3”我要利用这个字符串求得这个式子的得数,在Java里怎么用栈实现啊?求高手请教
------解决方案--------------------
for example
中缀表达式转后缀表达式
解析表达式并计算
for example
- Java code
import java.util.*;public class Test { public static void main(String[] args) throws Throwable { List<String> list = analyze("(5+6)*7+9/3"); //System.out.println(list); System.out.printf("%.2f\n", cacl(list)); } public static List<String> analyze(String exp) throws Exception { //中缀转后缀 if (exp == null) { throw new Exception ("illegal parameter."); } exp = exp.replaceAll("\\s*", ""); final String symbol = "+-*/()"; //运算符 final String[] priority = {"+-", "*/", "()"}; //优先级 Comparator<String> comp = new Comparator<String>() { //运算符优先级比较 public int compare(String s1, String s2) { int n1=0, n2=0; for (int i=0; i<priority.length; i++) { if (priority[i].indexOf(s1) >= 0) {n1 = i;} if (priority[i].indexOf(s2) >= 0) {n2 = i;} } return (n1 - n2); } }; List<String> list = new ArrayList<String>(); //后缀表达式结果 Stack<String> sym = new Stack<String>(); //运算符栈 StringBuilder buf = new StringBuilder(); for (char c : exp.toCharArray()) { if (symbol.indexOf(c) >= 0) { if (buf.length() > 0) { String v = buf.toString(); if (! v.matches("\\d+([.]\\d+)?")) { throw new Exception ("illegal varaible("+v+")."); } list.add(v); buf.delete(0, buf.length()); } if (c == '(') { sym.push(String.valueOf(c)); } else if (c == ')') { String last = ""; while (sym.size() > 0) { last = sym.pop(); if (last.equals("(")) { break; } else { list.add(last); } } if (!"(".equals(last)) { throw new Exception ("illegal express."); } } else if (sym.size() > 0) { String s = String.valueOf(c); String last = sym.peek(); if (last.equals("(") || comp.compare(s, last) > 0) { sym.push(s); } else { last = sym.pop(); list.add(last); sym.push(s); } } else { sym.push(String.valueOf(c)); } } else { buf.append(c); } } if (buf.length() > 0) { list.add(buf.toString()); } while (sym.size() > 0) { String last = sym.pop(); if ("()".indexOf(last) >= 0) { throw new Exception ("illigal express."); } list.add(last); } return list; } public static double cacl(List<String> list) throws Exception { //计算 final String symbol = "+-*/()"; Stack<Double> val = new Stack<Double>(); double result = 0; while (list.size() > 0) { String s = list.remove(0); if (symbol.indexOf(s) >= 0) { double d1 = val.pop(); double d2 = val.pop(); if ("+".equals(s)) { result = d2 + d1; } else if ("-".equals(s)) { result = d2 - d1; } else if ("*".equals(s)) { result = d2 * d1; } else if ("/".equals(s)) { result = d2 / d1; } else { throw new Exception ("illegal symbol("+s+")."); } val.push(result); } else { if (!s.matches("\\d+([.]\\d+)?")) { throw new Exception ("illegal variable("+s+")."); } val.push(Double.valueOf(s)); } } return result; }}