Peter Olsbourg
Peter Olsbourg

Reputation: 487

Limit Variable Value - best way

quick question,

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?

Upvotes: 0

Views: 11271

Answers (6)

Manuel Ortiz
Manuel Ortiz

Reputation: 693

Old question. I'll leave it in case anyone else needs it

I solved it with the annotations

@Max(value = 534)
@Min(value = -840)
private Short digits;

Upvotes: 0

Henrik Christensen
Henrik Christensen

Reputation: 534

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.max and 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.

input/output graph

Upvotes: 1

Nivas
Nivas

Reputation: 18364

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.

Upvotes: 1

Low Flying Pelican
Low Flying Pelican

Reputation: 6054

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.

Upvotes: 1

dan
dan

Reputation: 1

define two constants one for MIN one for MAX, and check always that your variable is inside them

Upvotes: 0

Thilo
Thilo

Reputation: 262842

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 assert keyword.

Upvotes: 4

Related Questions