what is the best and most effective way to limit a variable in range of, say, 534 and -840.
Do I use Math.max methods here too?
if (variable < -840 || variable > 534)
throw new IllegalArgumentException(variable + " is out of range");
If you want to be able to turn this off at runtime, take a look at the
I'm not very clear what you are asking but if it's a general scenario like a class variable, best and easiest way is to encapsulate your variable, and in the setter method check the variable and throw an exception if it's out of the range.
Math.max will a little bit more expensive, but more importantly will not very very straightforward to the reader.
if(number > MIN && number < MAX) is the most straightforward, and the best way of checking this.
define two constants one for MIN one for MAX, and check always that your variable is inside them
None of the existing answers helped me, so here is what I found (in case someone else is looking for the same):
Rather than throwing an error, this solution accepts input above and below the limits and simply outputs the clipped value.
Math.min can be helpful for doing this:
Math.max(Math.min(input, MAX), MIN)
Here are the three basic cases; one integer within the limit, one above, and one below:
static final int MIN= -840;
static final int MAX = 534;
int inputX = -892; // less than minNumber
int inputY = 290; // within range
int inputZ = 1234; // greater than maxNumber
System.out.println( Math.max(Math.min(inputX, MAX), MIN) ); // -840
System.out.println( Math.max(Math.min(inputY, MAX), MIN) ); // 290
System.out.println( Math.max(Math.min(inputZ, MAX), MIN) ); // 534
This graph shows how the input (x) and output (y) are related.