计算后缀表达式的值(栈应用二)

来源:互联网 发布:番禺网络推广 编辑:程序博客网 时间:2024/05/22 10:56
static double evalPostFix() {Stack<Double> s = new Stack<Double>();String token;Double a, b, result = 0.0;boolean isNumber;Scanner sc = new Scanner(System.in);token = sc.next();while (token.charAt(0) != '=') {try {isNumber = true;result = Double.parseDouble(token);} catch (Exception e) {isNumber = false;}if (isNumber)s.push(result);else {switch (token.charAt(0)) {case '+':a = s.pop();b = s.pop();s.push(a + b);break;case '-':a = s.pop();b = s.pop();s.push(a - b);break;case '*':a = s.pop();b = s.pop();s.push(a * b);break;case '/':a = s.pop();b = s.pop();s.push(a / b);break;case '^':a = s.pop();b = s.pop();s.push(Math.exp(a * Math.log(b)));break;}}token = sc.next();}return s.peek();}

0 0