如何检查一个整数是否在给定范围内?

发布于 2024-10-31 07:12:51 字数 77 浏览 2 评论 0原文

希望有比这更优雅的东西

if (i>0 && i<100) 

Hoping for something more elegant than

if (i>0 && i<100) 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(22

快乐很简单 2024-11-07 07:12:51

您可以添加间距;)

if (i > 0 && i < 100) 

You could add spacing ;)

if (i > 0 && i < 100) 
千紇 2024-11-07 07:12:51

对于那些使用 commons lang 的人来说,一个选项是使用 范围

Range<Integer> myRange = Range.between(100, 500);
if (myRange.contains(200)){
    // do something
}

另请参阅:如何构建 apache commons 3.1 Range;对象

For those using commons lang an option is to use Range:

Range<Integer> myRange = Range.between(100, 500);
if (myRange.contains(200)){
    // do something
}

Also see: how to construct a apache commons 3.1 Range<Integer> object

玩物 2024-11-07 07:12:51

我认为

if (0 < i && i < 100) 

更优雅。看起来像数学方程。

如果您正在寻找一些特别的东西,您可以尝试:

Math.max(0, i) == Math.min(i, 100)

至少它使用了库。

I think

if (0 < i && i < 100) 

is more elegant. Looks like maths equation.

If you are looking for something special you can try:

Math.max(0, i) == Math.min(i, 100)

at least it uses library.

狼性发作 2024-11-07 07:12:51

ValueRange

我们可以重新调整java.time.temporal.ValueRange 类位于 Java 8+ 内置的 java.time 框架中。

ValueRange range = java.time.temporal.ValueRange.of(minValue, maxValue);
range.isValidIntValue(x);

此代码:

  • 如果 minValue <= x <= MaxValue,则返回 true - 即在范围内
  • 如果 x x <= MaxValue,则返回 false minValue x > maxValue - 即超出范围

if 条件一起使用,如下所示:

int value = 10;
if (ValueRange.of(0, 100).isValidIntValue(value)) {
    System.out.println("Value is with in the Range.");
} else {
    System.out.println("Value is out of the Range.");
}

以下程序检查 hasTeen 方法中传递的任何整数值是否在范围内范围为 13(包含)到 19(包含)。


import java.time.temporal.ValueRange;
  
public class TeenNumberChecker {

    public static void main(String[] args) {
        System.out.println(hasTeen(9, 99, 19));
        System.out.println(hasTeen(23, 15, 42));
        System.out.println(hasTeen(22, 23, 34));
    }

    public static boolean hasTeen(int firstNumber, int secondNumber, int thirdNumber) {

        ValueRange range = ValueRange.of(13, 19);
        System.out.println("*********Int validation Start ***********");
        System.out.println(range.isIntValue());
        System.out.println(range.isValidIntValue(firstNumber));
        System.out.println(range.isValidIntValue(secondNumber));
        System.out.println(range.isValidIntValue(thirdNumber));
        System.out.println(range.isValidValue(thirdNumber));
        System.out.println("**********Int validation End**************");

        if (range.isValidIntValue(firstNumber) || range.isValidIntValue(secondNumber) || range.isValidIntValue(thirdNumber)) {
            return true;
        } else
            return false;
    }
}

输出

true 因为 19 是范围的一部分

true 因为 15 是范围的一部分

false 因为所有三个值均超出范围

ValueRange

We can repurpose the java.time.temporal.ValueRange class found within the java.time framework built into Java 8+.

ValueRange range = java.time.temporal.ValueRange.of(minValue, maxValue);
range.isValidIntValue(x);

This code:

  • Returns true if minValue <= x <= MaxValue - i.e. within the range
  • Returns false if x < minValue or x > maxValue - i.e. out of range

Use with if condition as shown below:

int value = 10;
if (ValueRange.of(0, 100).isValidIntValue(value)) {
    System.out.println("Value is with in the Range.");
} else {
    System.out.println("Value is out of the Range.");
}

The below program checks, if any of the passed integer value in the hasTeen method is within the range of 13 (inclusive) to 19 (inclusive).


import java.time.temporal.ValueRange;
  
public class TeenNumberChecker {

    public static void main(String[] args) {
        System.out.println(hasTeen(9, 99, 19));
        System.out.println(hasTeen(23, 15, 42));
        System.out.println(hasTeen(22, 23, 34));
    }

    public static boolean hasTeen(int firstNumber, int secondNumber, int thirdNumber) {

        ValueRange range = ValueRange.of(13, 19);
        System.out.println("*********Int validation Start ***********");
        System.out.println(range.isIntValue());
        System.out.println(range.isValidIntValue(firstNumber));
        System.out.println(range.isValidIntValue(secondNumber));
        System.out.println(range.isValidIntValue(thirdNumber));
        System.out.println(range.isValidValue(thirdNumber));
        System.out.println("**********Int validation End**************");

        if (range.isValidIntValue(firstNumber) || range.isValidIntValue(secondNumber) || range.isValidIntValue(thirdNumber)) {
            return true;
        } else
            return false;
    }
}

OUTPUT

true as 19 is part of range

true as 15 is part of range

false as all three value passed out of range

花开雨落又逢春i 2024-11-07 07:12:51

我认为这已经是比较范围的优雅方式。但是,这种方法会导致您编写额外的单元测试来满足所有 && 情况。

因此,您可以使用以下任何方法来避免编写额外的单元测试。

使用 Java 8 Streams:

if(IntStream.rangeClosed(0,100).boxed().collect(Collectors.toList()).contains(i))

使用 Math 类:

if(Math.max(0, i) == Math.min(i, 100))

我个人推荐第二种方法,因为它最终不会创建一个大小等于您要检查的范围的数组。

I think its already elegant way for comparing range. But, this approach cause you to write extra unit tests to satisfy all && cases.

So, you can use any of the below approach to avoid writing extra unit tests.

Using Java 8 Streams:

if(IntStream.rangeClosed(0,100).boxed().collect(Collectors.toList()).contains(i))

Using Math class:

if(Math.max(0, i) == Math.min(i, 100))

Personally I recommend the second approach because it won't end up creating an Array of the size equal to the range you want to check.

疾风者 2024-11-07 07:12:51

我不认为这不优雅,但如果您经常重复该表达式,那么最好将其放入方法中,例如,

class MathUtil
{
   public static boolean betweenExclusive(int x, int min, int max)
   {
       return x>min && x<max;    
   }
}

如果您混合独占比较和包含比较,则尤其如此。方法名称可以帮助避免拼写错误,例如使用 <当 <= 应该被使用时。该方法还可以确保min<0。最大等..

I don't see how that's not elegant, but if you repeat the expression often, then it's a good idea to put it into a method, e.g.

class MathUtil
{
   public static boolean betweenExclusive(int x, int min, int max)
   {
       return x>min && x<max;    
   }
}

This is particularly true if you mix exclusive and inclusive comparisons. The method name can help avoid typos, such as using < when <= should have been used. The method can also take care of ensuring that min < max etc..

不可一世的女人 2024-11-07 07:12:51

如果您正在寻找比

if (i > 0 && i < 100)

您更原创的东西,可以尝试这个

import static java.lang.Integer.compare;
...
if(compare(i, 0) > compare(i, 100))

If you're looking for something more original than

if (i > 0 && i < 100)

you can try this

import static java.lang.Integer.compare;
...
if(compare(i, 0) > compare(i, 100))
迷迭香的记忆 2024-11-07 07:12:51

这家伙做了一个不错的< href="https://headcrashing.wordpress.com/2011/01/01/range-class/" rel="nofollow noreferrer">范围 类。

然而,它的使用不会产生好的代码,因为它是一个通用类。你必须输入类似这样的内容:

if (new Range<Integer>(0, 100).contains(i))

or (如果你先实现的话会更好一些):

class IntRange extends Range<Integer>
....
if (new IntRange(0,100).contains(i))

恕我直言,语义上两者都比 Java 默认提供的更好,但是内存开销、性能下降和更多的打字总体上是值得的。就我个人而言,我更喜欢 mdma 的方法

This guy made a nice Range class.

Its use however will not yield nice code as it's a generic class. You'd have to type something like:

if (new Range<Integer>(0, 100).contains(i))

or (somewhat better if you implement first):

class IntRange extends Range<Integer>
....
if (new IntRange(0,100).contains(i))

Semantically both are IMHO nicer than what Java offers by default, but the memory overhead, performance degradation and more typing overall are hadly worth it. Personally, I like mdma's approach better.

云淡风轻 2024-11-07 07:12:51

Google 的 Java 库 Guava 还实现了 Range< /a>:

import com.google.common.collect.Range;

Range<Integer> open = Range.open(1, 5);
System.out.println(open.contains(1)); // false
System.out.println(open.contains(3)); // true
System.out.println(open.contains(5)); // false

Range<Integer> closed = Range.closed(1, 5);
System.out.println(closed.contains(1)); // true
System.out.println(closed.contains(3)); // true
System.out.println(closed.contains(5)); // true

Range<Integer> openClosed = Range.openClosed(1, 5);
System.out.println(openClosed.contains(1)); // false
System.out.println(openClosed.contains(3)); // true
System.out.println(openClosed.contains(5)); // true

Google's Java Library Guava also implements Range:

import com.google.common.collect.Range;

Range<Integer> open = Range.open(1, 5);
System.out.println(open.contains(1)); // false
System.out.println(open.contains(3)); // true
System.out.println(open.contains(5)); // false

Range<Integer> closed = Range.closed(1, 5);
System.out.println(closed.contains(1)); // true
System.out.println(closed.contains(3)); // true
System.out.println(closed.contains(5)); // true

Range<Integer> openClosed = Range.openClosed(1, 5);
System.out.println(openClosed.contains(1)); // false
System.out.println(openClosed.contains(3)); // true
System.out.println(openClosed.contains(5)); // true
回忆凄美了谁 2024-11-07 07:12:51
if ( 0 < i && i < 100)  

if ( 'a' <= c && c <= 'z' )
if ( 0 < i && i < 100)  

if ( 'a' <= c && c <= 'z' )
萌辣 2024-11-07 07:12:51

使用此代码:

if (lowerBound <= val && val < upperBound)
or
if (lowerBound <= val && val <= upperBound)

Use this code :

if (lowerBound <= val && val < upperBound)
or
if (lowerBound <= val && val <= upperBound)
风渺 2024-11-07 07:12:51

只是我的 2 cts

    // Exclusive    
    public boolean isOrdered(int n1, int n2, int n3) {
        return n1 < n2 && n2 < n3 ;
    }

称它为 1 到 99 之一

    if (isOrdered(0,i,100)) 

Just my 2 cts

    // Exclusive    
    public boolean isOrdered(int n1, int n2, int n3) {
        return n1 < n2 && n2 < n3 ;
    }

call it like to see it is one of 1 to 99

    if (isOrdered(0,i,100)) 
日记撕了你也走了 2024-11-07 07:12:51

如果您使用 Spring 数据,您还可以使用 Spring 中的 Range 对象。

range = new org.springframework.data.domain.Range(3, 8);
range.contains(5) // will return true.

if you are using Spring data you can also use the Range object from Spring.

range = new org.springframework.data.domain.Range(3, 8);
range.contains(5) // will return true.
爱要勇敢去追 2024-11-07 07:12:51

这就是检查整数是否在范围内的方法。大于下限,小于上限。试图巧妙地进行减法可能不会达到您想要的效果。

That's how you check is an integer is in a range. Greater than the lower bound, less than the upper bound. Trying to be clever with subtraction will likely not do what you want.

南七夏 2024-11-07 07:12:51

尝试一下:

if (i>0 && i<100) {} 

至少会起作用;)

Try:

if (i>0 && i<100) {} 

it will work at least ;)

喜你已久 2024-11-07 07:12:51

如果您只是想测试 i 的值是否在 [0..100) 范围内,并且想要布尔结果,那么

i >= 0 && i < 100

就可以,并且会给您 true。如果您愿意在值超出范围时抛出异常,您可以使用内置的 checkIndex 方法,

Objects.checkIndex(i, 100)

如果超出范围,将抛出 IndexOutOfBoundsException 。诚然,这不是一个通用的解决方案,并且只有在您的上下文是为检查数组边界而进行范围检查的上下文中才真正更漂亮,但它的优点是不需要任何第三方库,这对于小型程序。

If you just want to test whether the value of i is in the range [0..100), and you want the boolean result, then

i >= 0 && i < 100

is fine and will give you true or false. If you are willing to throw an exception if the value is out of range, you can use the built-in checkIndex method

Objects.checkIndex(i, 100)

which will throw IndexOutOfBoundsException if out of range. Granted, it is not a general solution, and is really only prettier if your context is one in which your range check is being done for checking array bounds, but it has the advantage of not needed any third party libraries, which is nice for small programs.

遗心遗梦遗幸福 2024-11-07 07:12:51

试试这个如果策略。看起来很扎实。

int num = 5;
    
    //random values; can be changed
    int a = 3;
    int b = 7;
    
    if (num >= 3 && num <= 7) {
        //Your Code Here
    }

Try this if strategy. Seems solid.

int num = 5;
    
    //random values; can be changed
    int a = 3;
    int b = 7;
    
    if (num >= 3 && num <= 7) {
        //Your Code Here
    }
怀中猫帐中妖 2024-11-07 07:12:51

编写此程序是为了根据范围检查 3 个整数参数的值

我创建了一个单独的方法来使用 if/else-if 语句检查每个值的范围。

我希望这对某人有帮助。

public class TeenNumberChecker {

    public static void main(String[] args) {
        
        boolean isTeen = hasTeen();

    }

    public static boolean hasTeen(int valueOne, int valueTwo, int valueThree) {
        
        
        if (valueOne > 13 && valueOne < 19) {
            
            return true;
            
        } else if (valueTwo > 13 && valueTwo < 19) {
            
            return true;
            
        } else if (valueThree > 13 && valueThree < 19) {
            
            return true;
            
        }else {
            
            return false;
            
        }

    }
}

Wrote this program to check the value of 3 integer parameters against a range.

I have created a separate method to check the range of the each value using if/else-if statements.

I hope this helps someone.

public class TeenNumberChecker {

    public static void main(String[] args) {
        
        boolean isTeen = hasTeen();

    }

    public static boolean hasTeen(int valueOne, int valueTwo, int valueThree) {
        
        
        if (valueOne > 13 && valueOne < 19) {
            
            return true;
            
        } else if (valueTwo > 13 && valueTwo < 19) {
            
            return true;
            
        } else if (valueThree > 13 && valueThree < 19) {
            
            return true;
            
        }else {
            
            return false;
            
        }

    }
}
稚气少女 2024-11-07 07:12:51

好吧,这是一个很老的问题,有很多解决方案。 另一个(您可以决定这是否更优雅)

if (Math.max(lower, Math.min(value, higher)) == value)

这是OP示例中的

if (Math.max(0, Math.min(i, 100)) == i)

:但我认为这与使用库的任何其他解决方案一样庞大。

Ok, this is a quite old question, and there are many solutions. Here another one (you may decide if this is more elegant or not)

if (Math.max(lower, Math.min(value, higher)) == value)

in the example of the OP:

if (Math.max(0, Math.min(i, 100)) == i)

But I think this is so bulky like any other solution using a library.

甩你一脸翔 2024-11-07 07:12:51
 Range<Long> timeRange = Range.create(model.getFrom(), model.getTo());
    if(timeRange.contains(systemtime)){
        Toast.makeText(context, "green!!", Toast.LENGTH_SHORT).show();
    }
 Range<Long> timeRange = Range.create(model.getFrom(), model.getTo());
    if(timeRange.contains(systemtime)){
        Toast.makeText(context, "green!!", Toast.LENGTH_SHORT).show();
    }
战皆罪 2024-11-07 07:12:51

if(i <= 0 || i >=100)

它将起作用。

if(i <= 0 || i >=100)

It will work.

隔纱相望 2024-11-07 07:12:51

如果您确信数字以 2 的补码形式存储:

return  ((x-low) <= (high-low));

更通用、更安全的解决方案是:

return ((x-high)*(x-low) <= 0);

If you are confident that numbers are stored in 2's complement form:

return  ((x-low) <= (high-low));

A more general and safer solution would be:

return ((x-high)*(x-low) <= 0);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文