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?

-------------Problems Reply------------

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.

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

Limit Variable Value - best way

Category:java Views:0 Time:2011-08-03
Tags: java

Related post

  • Named blocks to limit variable scope: good idea? 2008-10-15

    For years, I've been using named blocks to limit the scope of temporary variables. I've never seen this done anywhere else, which makes me wonder if this is a bad idea. Especially since the Eclipse IDE flags these as warnings by default. I've used th

  • How to limit variable in ruby? 2011-02-04

    How can I limit a variable that belongs to new Class < Fixnum, between 0 and 255? Or if I can't create a limit in subclass of Fixnim how to write my own class with limit? --------------Solutions------------- Write a non inherited class and use met

  • Undeclared variable error when using a LIMIT variable with PREPARE in MySQL 2012-04-08

    I'm writing a stored procedure. I am having some problems using a variable in combination with LIMIT and a prepared statement. (See code below) The procedure is created normally, but when I call it I get an error that variable a is undeclared. Any su

  • How to Limit Variable Scope 2010-10-22

    Possible Duplicate: Limiting variable scope Is there a way to force R to ignore all objects set in the global environment? For example, let's say I have 'df' as an object outside of my function and I wish to use the same shorthand within my function,

  • How can I limit variable size in to maximium of 32 KB in Oracle Forms? 2011-02-09

    I am working with Oracle Forms 6i and I want to limit the size of the return value of a functions in to 32KB. How can I do this ? --------------Solutions------------- If you're calling a function that returns a VARCHAR2, it's already limited to 32,76

  • jquery passing a variable to a function 2010-02-18

    Hay guys, I'm making a simple preload function (function($) { $.fn.preload = function(settings) { var config = { before: function(){ return; }, end: function(){ return; }, after: function(a){ return; } }; if (settings) $.extend(config, settings); var

  • Jquery script doesnt evaluate element variable 2011-02-22

    $(".panel_wager_container input").change(function(event) { var wager = $(this).val(); var multiplier = $('#multiplier').html(); var limit = 15.00; var winnings = $("#potential_winnings").val(); if(wager - 0 == wager && wager.length > 0) {

  • Stuck in MYSQL procedure using 'order by variable' 2011-04-04

    this is paramater IN `_user_id` VARCHAR(50), IN `_page` INT, IN `_sort_type` VARCHAR(50), IN `_order_type` VARCHAR(50) and this is procedure BEGIN if _page < 0 then set _page = 0; end if; if _sort_type='idx' then set _sort_type = '__idx'; end if;

  • MYSQL can I change how to LIMIT results dynamicly? 2011-04-06

    Instead of hardcoding querry: LIMIT 3, i would like to get LIMIT number different every time i press the button. Thats what i got so far: $region=$_GET["region"]; $number=$_GET["limit"]; $con = mysql_connect('localhost') or die(mysql_error()); mysql_

  • How do I not share an external variable across instances? 2011-06-26

    EDIT: this is a rewrite of the question since it was so unspecific before. So I'm having a problem solving the issue of variables being shared across instances in C extensions. Here is an example of what I'm encountering. >> t = SCOPE::TestClas

  • Strawberry Perl Memory Limit? 2011-12-09

    I'm running a perl script to pull a list of about 20 text files, and parse through them. For some reason my process is bombing partway through the list, and am having trouble debugging it. Anyone know the location of the Strawberry perl log file, and

  • Declaring variables inside or outside of a loop 2012-01-10

    Why is this: String str; while(condition){ str = calculateStr(); ..... } better than this? while(condition){ String str = calculateStr(); ..... } Is it necessary to declare variables outside the loop? --------------Solutions------------- The scope of

  • Is it better to declare a variable inside the loop or outside the loop? 2012-02-03

    Possible Duplicate: Difference between declaring variables before or in loop? Consider the two codes below : Object i; for(int i=0;i<10;i++){ i = new Object(); } OR for(int i=0;i<10;i++){ Object i = new Object(); } which of the two codes above

  • Set and reduce a variable in function call 2013-06-24

    I am trying to use a variable to set a limit to the number of times a variable is called. For example, I'm trying to poll a url, but I only want to do this a few times before I escape the loop. # Javascript file. @poller = poll: -> setTimeout @req

  • What data structure is behind FD_SET and FD_ISSET when working with sockets in c? 2009-04-01

    What data structure is behind FD_SET and FD_ISSET macro when working with sockets? --------------Solutions------------- Prototypes: void FD_SET(int fd, fd_set* fdset); int FD_ISSET(int fd, fd_set* fdset); From sys/select.h typedef struct fd_set { u_i

  • Digit limitation from decimal point in C++ 2009-04-28

    I'm new in C++.I have double variable double a=0.1239857 I want to limit variable a from decimal point two digits.So a will be 0.12. I know C++ have functions that return largest or smallest integer that is greater or lower than a like ceil or floor.

  • How to add greater than/less than to Hibernate filters 2009-06-26

    How can you add greater than or less than symbols to the condition on a Hibernate filter specified in the hbm.xml file? I am trying to add a filter to limit the collection to a specific date range: <filter name="limitTalksByDateRange" condition="t

  • How does the (function() {})() construct work and why do people use it? 2009-10-28

    (function() {})() and its jQuery-specific cousin (function($) {})(jQuery) pop up all the time in Javascript code. How do these constructs work, and what problems do they solve? Examples appreciated --------------Solutions------------- With the increa

  • importance of function wrappers in javascript 2009-12-19

    Can someone explain to me the importance of using function wrappers (ie: when assigning onclick functionality)? I know I should, but I don't fully understand why... Example: It's my understanding that this: $(callingImg)[0].setAttribute("onclick", "f

Copyright (C), All Rights Reserved.

processed in 0.125 (s). 11 q(s)