How to tell my program, that an integer-value shall never exceed 100?

edited July 2015 in How To...

A simple question: How can i tell my program, that int "a" shall never exceed 100?

Tagged:

Answers

  • edited July 2015

    Java doesn't provide us some automatic datatype w/ customized limits.
    What we can do is apply min() as limit clamping for every single time some variable is reassigned:

    int a = 50, x = (int) random(100);
    println(a, x);
    
    a = min(a + x, 100);
    println(a);
    
    exit();
    
  • Answer ✓
     x = constrain(x, x, 100); // ??? UNTESTED.
    
  • Answer ✓

    Could create a Java class to do it

    public final class RangedInt {
    
      private final int min;
      private final int max;
      private int value;
    
      public RangedInt (int initValue, int minValue, int maxValue) {
        min = minValue;
        max = maxValue;
        set (initValue);
      }
    
      public set (int v){
        if (v > max)
          v = max;
        else if(v < min)
          v = min;
      }
    
      public int get (){
        return value;
      }
    
    }
    

    Then create the variable

    RangedInt rint = new RangedInt (50, 0, 100);
    rint.set(111);
    println (rint.grt ()); // will display 100

    I have not tested the code so there maybe syntax errors but the symantics is ok.

    The advantage of this technique is that the user does not have to remember to limit the value it is done automatically. In a simple sketch this is probably over-the-top but useful technique to be aware of. :)

Sign In or Register to comment.