美文网首页
任意四则运算

任意四则运算

作者: 万福来 | 来源:发表于2020-06-02 19:21 被阅读0次

任意四则运算

// 任意四则运算
    public static Integer calculate(String str) {
        char[] chars = str.toCharArray();
        List<String> list = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            if (Character.isDigit(chars[i]) || chars[i] == '*' || chars[i] == '/') {
                sb.append(chars[i]);
            } else {
                list.add(sb.toString());
                sb.setLength(0);
                list.add(String.valueOf(chars[i]));
            }
        }
        if(sb.length() > 0){
            list.add(sb.toString());
            sb.setLength(0);
        }
        List<String> finList = new ArrayList<>();
        for (String cal : list) {
            if (cal.contains("*")) {
                String[] arr = cal.split("\\*");
                Integer num = Integer.valueOf(arr[0]) * Integer.valueOf(arr[1]);
                finList.add(num.toString());
            } else if (cal.contains("/")) {
                String[] arr = cal.split("/");
                Integer num = Integer.valueOf(arr[0]) / Integer.valueOf(arr[1]);
                finList.add(num.toString());
            } else {
                finList.add(cal);
            }
        }

        Integer result = 0;
        boolean add = true;
        for(String n : finList){
            if("+".equals(n)){
                add = true;
            }else if("-".equals(n)){
                add = false;
            }else{
                if(add){
                    result += Integer.valueOf(n);
                }else{
                    result -= Integer.valueOf(n);
                }
            }
        }
        return result;
    }

相关文章

网友评论

      本文标题:任意四则运算

      本文链接:https://www.haomeiwen.com/subject/pnspzhtx.html