继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

android计算器带有连续运算功能,四则运算有规律

car
关注TA
已关注
手记 83
粉丝 56
获赞 363
public double calc(String exp) {
        String regex = MainActivity.PLUSE + "|" + MainActivity.MINUS + "|"
                + MainActivity.MULTIPLY + "|" + MainActivity.DIVIDE;
        String[] strings = exp.split(regex);
        double[] nums = new double[strings.length];
        for (int i = 0; i < nums.length; i++) {
            nums[i] = Double.parseDouble(strings[i].trim());
        }
        List<String> opList = new ArrayList<String>();
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(exp);
        while (matcher.find()) {
            opList.add(matcher.group());
        }

        String string;
        String[] ops = new String[opList.size()];
        for (int i = 0; i < ops.length; i++) {
            ops[i] = opList.get(i);
        }

        double temp;
        for (int i = 0; i < ops.length - 1; ++i) {
            for (int j = 0; j < ops.length - 1 - i; ++j) {
                if (ops[j].compareTo(ops[j + 1]) > 0) {
                    string = ops[j];
                    ops[j] = ops[j + 1];
                    ops[j + 1] = string;
                    temp = nums[j];
                    nums[j] = nums[j + 1];
                    nums[j + 1] = temp;
                    temp = nums[j + 1];
                    nums[j + 1] = nums[j + 2];
                    nums[j + 2] = temp;
                }
            }
        }
        double result = nums[0];
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < ops.length; i++) {
            builder.append(ops[i]);
            builder.append(nums[i + 1]);
        }

        exp = nums[0] + builder.toString();
        strings = exp.split(regex);
        nums = new double[strings.length];
        for (int i = 0; i < nums.length; i++) {
            nums[i] = Double.parseDouble(strings[i].trim());
        }

        for (int i = 0; i < ops.length; ++i) {
            if (MainActivity.MULTIPLY.equals(ops[i])) {
                nums[0] *= nums[i + 1];
            } else if (MainActivity.DIVIDE.equals(ops[i])) {
                if (nums[i + 1] != 0) {
                    nums[0] /= nums[i + 1];
                }
            } else if (MainActivity.PLUSE.equals(ops[i])) {
                nums[0] += nums[i + 1];

            } else if (MainActivity.MINUS.equals(ops[i])) {
                nums[0] -= nums[i + 1];
            }
        }
        result = nums[0];
        return result;
    }
算法思想

根据运算符的顺序重新排列数据

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP