Herramientas comunes (15) -Cálculo de expresiones matemáticas y herramientas de cálculo de expresiones bool

public class ParseRuleUtils {
    
    


    static Boolean getBoolResult(String str) {
    
    

        if (str.contains("and") || str.contains("or")) {
    
    
            if (str.contains("and")) {
    
    
                int lIndex = str.lastIndexOf("and");

                int rIndex = lIndex + "and".length();
                boolean first = getBoolResult(str.substring(0, lIndex));
                boolean sec = getBoolResult(str.substring(rIndex + 1));
                return first && sec;
            } else {
    
    
                int lIndex = str.lastIndexOf("or");

                int rIndex = lIndex + "or".length();
                boolean first = getBoolResult(str.substring(0, lIndex));
                boolean sec = getBoolResult(str.substring(rIndex + 1));
                return first || sec;
            }
        } else {
    
    
            return Boolean.parseBoolean(str.trim());
        }
    }

    static boolean isNumber(String str) {
    
    //判断表达式是不是只有一个数字
        for (int i = 0; i < str.length(); i++) {
    
    
            if (!Character.isDigit(str.charAt(i)) && str.charAt(i) != '.') return false;
        }
        return true;
    }

    static Double getResult(String str) {
    
    
        if (str.isEmpty() || isNumber(str)) {
    
    //递归头
            return str.isEmpty() ? 0 : Double.parseDouble(str);
        }

        //递归体
        if (str.contains(")")) {
    
    
            int lIndex = str.lastIndexOf("(");//最后一个左括号
            int rIndex = str.indexOf(")", lIndex);//对于的右括号
            return getResult(str.substring(0, lIndex) + getResult(str.substring(lIndex + 1, rIndex)) + str.substring(rIndex + 1));
        }
        if (str.contains("+")) {
    
    
            int index = str.lastIndexOf("+");
            return getResult(str.substring(0, index)) + getResult(str.substring(index + 1));
        }
        if (str.contains("-")) {
    
    
            int index = str.lastIndexOf("-");
            return getResult(str.substring(0, index)) - getResult(str.substring(index + 1));
        }
        if (str.contains("*")) {
    
    
            int index = str.lastIndexOf("*");
            return getResult(str.substring(0, index)) * getResult(str.substring(index + 1));
        }
        if (str.contains("/")) {
    
    
            int index = str.lastIndexOf("/");
            return getResult(str.substring(0, index)) / getResult(str.substring(index + 1));
        }
        return null;//出错
    }
}

Supongo que te gusta

Origin blog.csdn.net/qq_36382679/article/details/112861673
Recomendado
Clasificación