头图

For open and closed intervals, the expressions in mathematics are usually () and [] . The parentheses represent the open interval, and the square brackets represent the closed interval. The difference between them is whether they contain the = equals sign. The open and closed intervals are usually divided into Some of the following situations:

  • (1, 10): represents 1 < x < 10;
  • (1, 10]: represents 1 < x <= 10;
  • [1, 10]: means 1 <= x <= 10;
  • [1, 10): means 1 <= x < 10;
  • (1, ) or (1, ]: represents x > 1;
  • [1, ] or [1, ): represents x >= 1;
  • (, 10) or [, 10): represents x < 10;
  • (, 10] or [, 10]: means x <= 10;

So how to use Java to determine whether a value is within the specified opening and closing interval? It can be achieved in the following way:

  • Since the opening and closing intervals have certain rules, the opening and closing intervals must be legal. Except for (,), [,], , , and numbers , other characters are illegal, so you need to check the opening and closing first. the legitimacy of the interval;
  • After it is determined that the opening and closing interval is legal, the minimum and maximum values of the opening and closing interval are split;
  • According to whether the opening and closing interval contains [], it is necessary to add = sign when judging;

1. Validation of open and closed intervals

The legitimacy of the opening and closing intervals can be verified by regular expressions. The specific regular expressions are as follows:

 /**
 * 开闭区间正则表达式
 */
private static final Pattern NUM_RANGE_PATTERN = Pattern.compile("[\\[|\\(]\\s?\\d+\\s?,\\s?\\d+\\s?[\\)|\\]]");

The legal regular expression of the left half open and closed interval is as follows:

 /**
 * 左半区间正则表达式
 */
private static final Pattern LEFT_NUM_RANGE_PATTERN = Pattern.compile("[\\[|\\(]\\s?\\d+\\s?,\\s?[\\)|\\]]");

The legal regular expression for the right half open and closed interval is as follows:

 /**
 * 右半区间正则表达式
 */
private static final Pattern RIGHT_NUM_RANGE_PATTERN = Pattern.compile("[\\[|\\(],\\s?\\d+\\s?[\\)|\\]]");

The code of the function method for judging the opening and closing interval is as follows:

 /**
 * 判断是否为有效的数字区间范围
 * @param numRange 数字区间
 * @return boolean
 */
public static boolean isValidNumRange(String numRange) {
    return NUM_RANGE_PATTERN.matcher(numRange).matches()
            || LEFT_NUM_RANGE_PATTERN.matcher(numRange).matches()
            || RIGHT_NUM_RANGE_PATTERN.matcher(numRange).matches();
}

2. Judgment method

 /**
 * 判断数值是否在区间范围内
 * @param number 数值
 * @param numRange 开闭区间
 * @return boolean
 */
public static boolean inNumRange(int number, String numRange) {
    Objects.requireNonNull(numRange);

    if (!isValidNumRange(numRange)) {
        return false;
    }

    String[] pairs = numRange.split(",");

    // 获取开闭区间的最小值和最大值
    List<String> rangeNums = Arrays.stream(pairs).map(str -> str.replaceAll("[(|)|\\[|\\]]", "").trim()).collect(Collectors.toList());
    Integer minValue = "".equals(rangeNums.get(0)) ? null : Integer.valueOf(rangeNums.get(0));
    Integer maxValue = "".equals(rangeNums.get(1)) ? null : Integer.valueOf(rangeNums.get(1));

    // 判定数值是否大于最小值
    boolean minMatched = (minValue == null) || (pairs[0].startsWith("[") ? number >= minValue : number > minValue);
    // 判定数值是否小于最大值
    boolean maxMatched = (maxValue == null) || (pairs[1].endsWith("]") ? number <= maxValue : number < maxValue);

    return minMatched && maxMatched;
}

3. Test verification

 public static void main(String[] args) {
        System.out.println(inNumRange(1, "(0, 2]"));
        System.out.println(inNumRange(1, "(, 2]"));
        System.out.println(inNumRange(1, "(1, 4]"));
        System.out.println(inNumRange(1, "(0, ]"));
    }

Run the program and output the following results:

 true
true
false
true

十方
226 声望433 粉丝