手记

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

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;
    }
算法思想

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

0人推荐
随时随地看视频
慕课网APP