编写一个程序计算后缀表达式的值

来源:互联网 发布:管家婆数据导入失败 编辑:程序博客网 时间:2024/05/25 21:35
public static double evalFix(){        Stack<Double> stack=new Stack<>();        String token;        Double a,b,result=0.0;        Scanner scanner=new Scanner(System.in);        token=scanner.next();        boolean isNumber;        while(token.charAt(0)!='='){            try {                isNumber=true;                result=Double.parseDouble(token);            } catch (NumberFormatException e) {                isNumber=false;            }            if(isNumber){                stack.push(result);            }else{                switch(token.charAt(0)){                    case '+':a=stack.pop();b=stack.pop();                              stack.push(a+b);break;                    case '-':a=stack.pop();b=stack.pop();                              stack.push(a-b);break;                    case '*':a=stack.pop();b=stack.pop();                              stack.push(a*b);break;                    case '/':a=stack.pop();b=stack.pop();                              stack.push(a/b);break;                    case '^':a=stack.pop();b=stack.pop();                              stack.push(Math.pow(a,b));break;                }            }            token=scanner.next();        }        return stack.peek();    }