日期:2014-05-20  浏览次数:20810 次

如何用递归方法实现postfix计算?
譬如说在cmd下输入
java postfixCal 23+4-
会得到1?

------解决方案--------------------
Java code


import java.util.LinkedList;
import java.util.List;


public class PostFix {


    public static void main(String[] args) {
        
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<args.length;i++)
            sb.append(args[i]+" ");
        System.out.println(calPostFix(sb.toString()));

    }
    private static double calPostFix(String str)
    {
        
        List<String> parts = new LinkedList<String>();
        for(int i=0;i<str.length();)
        {
            if(str.charAt(i)==' ')
            {
                i++;
                continue;
            }
            int pos = i;
            while(Character.isDigit(str.charAt(i))  || str.charAt(i)=='.') //数字
                i++;
            if(pos!=i)
            {
                parts.add(str.substring(pos, i));
                continue;
            }
            //操作符
            parts.add(str.charAt(i++)+"");
            
        }
        
        double nowValue = Double.parseDouble(parts.get(0));
        return calPostFixParts(parts, 1, nowValue);
        
        
    }
        /**这里递归调用**/
    private static double calPostFixParts(List<String> parts, int pos, double nowValue)
    {
        if(pos>=parts.size())
            return nowValue;
        
        double res = cal(nowValue, parts.get(pos), parts.get(pos+1));
        return calPostFixParts(parts, pos+2, res);
    }

    protected static double cal(double m, String b, String operator)
    {
        if(operator.length()!=1)
            throw new RuntimeException("操作符不合法");
        
        Character op = operator.charAt(0);
        double n = Double.valueOf(b);
        switch(op)
        {
        case '+':return m+n;
        case '-':return m-n;
        case '*':return m*n;
        case '/':return m/n;
        case '^':return Math.pow(m, n);
        default:throw new RuntimeException("操作符不合法");
        }
    }

}