双栈算术表达式求值

算术表达式求值:

public class Evaluate
{
    public static void main(String[] args)
    {
        Stack<String> ops =new Stack<String>();
        Stack<Double> vals=new Stack<Double>();
        while(!StdIn.isEmpty())
        {
            String s=StdIn.readString();
            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("sqrt"))  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.sqart(v);
                vals.push(v);
            }
            else vals.push(Double.parseDouble(s));
        }
     StdOut.println(vals.pop());
    }
}

 

上一篇:20190919-6 四则运算试题生成,结对


下一篇:20190919-4 单元测试,结对