简体   繁体   English

如何在 Java 中表示整数间隔?

[英]How can I represent integer intervals in Java?

We all know about intervals in mathematics (eg -4 < x < 3).我们都知道数学中的区间(例如 -4 < x < 3)。

How can I represent these mathematic intervals in Java, eg, the numbers between -4 and 3 (-4, -3, ..., 2, 3 etc)?我如何用 Java 表示这些数学区间,例如,-4 和 3 之间的数字(-4、-3、...、2、3 等)?

Check apache commons-lang IntRange .检查 apache commons-lang IntRange So, if you want to check if a number is in a given interval (range), you do:所以,如果你想检查一个数字是否在给定的间隔(范围)内,你可以:

IntRange range = new IntRange(-4, 3);
if (range.contains(x)) {
   ....
}

You simply have to separate -4 < x < 3 into -4 < x and x < 3 , like this:您只需将-4 < x < 3分成-4 < xx < 3 ,如下所示:

if (-4 < x && x < 3)
{
. . .
}

Google Guava 还有一个 Range 类( https://guava.dev/releases/19.0/api/docs/com/google/common/collect/Range.html )可能适合您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM