Dijkstra的双栈算术表达式求值算法
public class Evaluate{ public static void main(String[] args){ Stack<String> ops = new Stack<String>(); Stack<Double> vals = new Stack<Double>(); Scanner in = new Scanner(System.in); while (in.hasnext()){ String s = in.nextString(); if (s.equals("(")) ; else if (s.equals("+")) ops.push(s); else if (s.equals("-")) ops.push(s); else if (s.equals("*")) ops.push(s); else if (s.equals("/")) ops.push(s); else if (s.equals("sqart")) ops.push(s); else if (s.equals(")")){ String op = ops.pop(); double v = vals.pop(); if (op.equals("+")) v = vals.pop()+v; else if (op.equals("-")) v = vals.pop()-v; else if (op.equals("*")) v = vals.pop()*v; else if (op.equals("/")) v = vals.pop()/v; else if (op.equals("sqrt")) v = Math.sqrt(v); vals.push(v); } else vals.push(Double.parseDouble(s)); } system.out.println(vals.pop()); } }