任意四则运算

任意四则运算

// 任意四则运算
    public static Integer calculate(String str) {
        char[] chars = str.toCharArray();
        List 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 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;
    }

你可能感兴趣的:(任意四则运算)