java实现逆波兰式四则运算

package stack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

import stack.Stack; // or import java.util.Stack;

/**
 * 本例主要使用了数据结构中的栈来实现,栈的实现可以使用java.util.Stack,这里我使用了自己编写的栈
 * 另外本例也使用了java类集中的ArrayList和HashMap
 * 
 * @author jonhou
 * @version 2016年2月5日下午6:32:58
 */
public class RPNCalculator {
    private static HashMap<String, Integer> hm = new HashMap<String, Integer>(5);

    public RPNCalculator() {
        hm.put("+", 1);
        hm.put("-", 1);
        hm.put("*", 2);
        hm.put("/", 2);
        hm.put("%", 2);

    }

    private String[] split(String s) {
        String[] ss = null;
        StringBuilder strtmp = new StringBuilder();
        for (char x : s.toCharArray()) {
            if (x == '+' || x == '-' || x == '*' || x == '/' || x == ')' || x == '(') {
                strtmp.append(",");
                strtmp.append(x);
                strtmp.append(",");
            } else {
                strtmp.append(x);
            }
        }
        ss = strtmp.toString().replaceAll(",{2,}", ",").split(",");

        return ss;
    }

    /**
     * 判断输入的四则表达式格式是否合法
     * 
     * @param s
     * @return
     */
    private boolean isLegal(String s) {
        Stack<String> stack = new Stack<>();
        ArrayList<String> list = new ArrayList<String>(Arrays.asList(split(s)));
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).equals("(")) {
                list.remove(i);
                stack.push(list.get(i));
                i--;
            } else if (list.get(i).equals(")")) {
                if (stack.peek() == null) {
                    System.out.println("wrong expression too more )");
                    return false;
                } else {
                    stack.pop();
                    list.remove(i);
                    i--;
                }
            }
        }
        if (!stack.isEmpty()) {
            System.out.println("wrong expression too more (");
            return false;
        }
        if (!isNum(list.get(0))) {
            System.out.println("wrong expression first");
            return false;
        }
        System.out.println(list);
        for (int i = 0; i < list.size() - 1; i++) {
            if ((isNum(list.get(i)) && isNum(list.get(i + 1))) || (!isNum(list.get(i)) && !isNum(list.get(i + 1)))) {
                System.out.println("wrong expression double ");
                return false;
            }
        }
        return true;
    }

    private boolean isNum(String s) {
        for (char x : s.toCharArray()) {
            if (x >= '0' && x <= '9') {
                return true;
            }
        }
        return false;
    }

    /**
     * if top > x return true
     */
    private boolean isHigh(String top, String x) {

        if (x.equals("(") || top == null || top.equals("(")) {
            return false;
        }
        return hm.get(top) > hm.get(x);
    }

    public ArrayList<String> toRPN(String s) {
        if (!isLegal(s)) {
            System.exit(0);
        }
        ArrayList<String> RPN = new ArrayList<String>();
        Stack<String> stack = new Stack<String>();
        String[] strSplit = split(s);
        for (String x : strSplit) {
            if (isNum(x)) {
                RPN.add(x);
            } else {
                if (x.equals(")")) { // 出现右括号,出栈至(
                    while (!"(".equals(stack.peek())) {
                        RPN.add(stack.pop());
                    }
                    stack.pop();
                } else if (isHigh(stack.peek(), x)) {// 栈顶元素较大的时候出栈
                    RPN.add(stack.pop());
                    while (stack.peek() != null && !isHigh(x, stack.peek())) {// 将优先级比x大的和相等的出栈
                        RPN.add(stack.pop());
                    }
                    stack.push(x);
                } else {
                    stack.push(x);
                }
            }

        }
        while (stack.peek() != null) {
            RPN.add(stack.pop());
        }
        return RPN;

    }

    public float calculate(String s) {
        ArrayList<String> RPN = toRPN(s);
        Stack<Float> stack = new Stack<Float>();
        for (String x : RPN) {
            if (isNum(x)) {
                stack.push(Float.valueOf(x));
            } else {
                float rear = stack.pop();
                float front = stack.pop();
                switch (x) {
                case "+":
                    stack.push(front + rear);
                    break;
                case "-":
                    stack.push(front - rear);
                    break;
                case "*":
                    stack.push(front * rear);
                    break;
                case "/":
                    stack.push(front / rear);
                    break;
                default:
                    System.out.println("wrong opration");
                }
            }
        }
        return stack.pop();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
/* 表达计算 */ /* 调用方:CalcExp('1+max(0.5,sin(1))+sum(1,2^3,mod(5,3))', res, infoStr) */ /* 带符号参数调用方法,先调用符号定义AddSignParam,再调用 CalcExp: */ /* AddSignParam(['a','s'], [1, 0.5]); 或者 AddSignParam('a=1,s=0.5') */ /* CalcExp('1+a+sin(s)', res, infoStr) */ /* 其中res存储计算结果,为double型;infoStr存储计算时的提示信息,为string */ 表达计算器 V2.3 支持以下功能: 1、四则运算 + - * / 、括弧()、正负(+ -) 2、百分数 %、求幂 ^ 、整数阶乘 ! (1 至 150) 3、参数符号计算,示例:a+b @@a=1,b=2 结算结果为3 用@@表示表达中定义符号的值 4、常数e、圆周率PI 5、丰富的函数功能: 统计函数: max,min,sum,avg,stddev 标准偏差,均支持多参数 三角函数: sin,cos,tan,arcsin,arccos,arctan degrad(60) 角度转弧度 raddeg(3.14) 弧度转角度 costh(a,b,c) 余弦定理 cosC) 指数对数函数:sqrt,power(x,y),abs,exp,log2,log10,logN(a,N),ln 数据处理函数:int(x),trunc(x) 取整 frac(x) 取小数部分 round(x) 四舍五入取整 roundto(x,-1) 保留一位小数 mod(M,N) 求模 几何面积函数:s_tria(a,b,c) 三角形面积 s_circ(r) 圆形面积 s_elli(a,b) 椭圆面积 s_rect(a,b) 矩形面积 s_poly(a,n) 正多边形面积 平面几何函数:pdisplanes(x1,y1,x2,y2) 平面两点距离 pdisspace(x1,y1,z1,x2,y2,z2) 空间两点 p_line(x0,y0, A, B, C) 平面点到线距离 p_planes(x0,y0,z0 A, B, C, D)空间点到面距离 数列求和: sn(a1, d, n) 等差数列前n项和 sqn(a1, q, n) 等比数列前n项和 个税计算函数:intax(x), arcintax(x) 个税反算 6 、历史计算记录,双击计算记录可重新修改计算 示例: sin(1)+(-2+(3-4))*20% , e^63+PI , 15! , log2(max(2,3)) 注: 运算符必须为半角格,三角函为弧度,输入可用空格间隔
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值