How to check if an int is within a range of values

Specifically, if-elseI need to determine if a given value falls into a range. Part of the condition is as follows:

else if (a==2 && b.equalsIgnoreCase("line")
     && <<Here I need to search if c falls within a range>> && d)

where a is int, b is a string, c is int, and d is Boolean. Now, if c falls in the range from 1 to 8, the condition is true, otherwise it is false. How can i do this?

+1
source share
5 answers

I think you need this condition for c

(c > 1 && c < 8) // 1 and 8 are exclusive
(c => 1 && c <= 8) // 1 and 8 are inclusive

Full sample

else if (a==2 && b.equalsIgnoreCase("line")
     && (c > 1 && c < 8) && d)

, , Set, , c . , , . , .

Integer[] arr = {1,4,9,11,13};
Set<Integer> set = new HashSet<>(Arrays.asList(arr));
...
else if (a==2 && b.equalsIgnoreCase("line")
     && (set.contains(c)) && d)
+2

, c >= low && c <= high

,

Set<Integer> validValues = new HashSet<Integer>();
validValues.add(1);
validValues.add(4);
validValues.add(9);
validValues.add(10);
validValues.add(19);

if (validValues.contains(currentVal)) {
    // do stuff
}

java-, Guava:

Set<Integer> validValues = ImmutableSet.of(1, 4, 9, 10, 19);
+3

, range1 range2 - , b.

(c < range1 && c >  range2) ? d=true : d=false;
0

:

c > 1 && c < 8

- , , , . , , , :

public boolean inRange(int num)
{
    return (num > 1 && num < 8);
}
0

, - if else ( ). switch , . , , , . , , -

public Boolean inRange(int num, int lowBound, int topBound)
{
    return (num > lowBound && num < topBound);

}

,

else if (a==2 && b.equalsIgnoreCase("line")
     && inBound(c, 1, 8) && d)

This does not look too confusing and will work (you will need to decide whether it is inclusive or exclusive restrictions included).

The reason for the modified method is that it can be used elsewhere, which makes it useful for checking the range.

0
source

Source: https://habr.com/ru/post/1625697/


All Articles