亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

android計算器帶有連續運算功能,四則運算有規律

標簽:
Java
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;
    }
算法思想

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

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
JAVA開發工程師
手記
粉絲
56
獲贊與收藏
363

關注作者,訂閱最新文章

閱讀免費教程

  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消