5

I have the attribute:

private int Number;

I want to limit this number so that it can only be between the values 1 - 3.

Would I do this within a method when I set the value or is there a way of predefining that I only want values 1 - 3 to be valid values for this integer?

Many thanks in advance.

Edit:

I want to take an input of a number between 1 -3.

I've tried using a while, do and for loop each of which I can't get to work without getting stuck in an infinite loop.

Here's some example code:

    private int Number;

    public void setNumber(int aNumber) {
        int count = 1;
        while (count !=0) {
            if ((aNumber < 1) || (aNumber > 3)) {
                System.out.println("Value is out of range 1-3");
                System.out.println("Please try again");
                break;
            } 
            else {
                this.Number = aNumber;
                count = 0;
            }
    }
}
silverzx
  • 1,209
  • 4
  • 14
  • 18
  • I have 2 questions. 1: That loop should never run infinitely as far as I can see. When are you getting an infinite loop? 2. Why is that loop there at all, since it can never run more than once. What did you intend? – Bart van Heukelom Dec 07 '11 at 19:16
  • If I put a number in which doesn't fit the criteria (between 1-3) then it infinitely loops my "Value is out or range 1-3" "Please try again" print outs. Reading through my own code it should be =< 1 || => 3 ? – silverzx Dec 07 '11 at 19:26
  • The condition doesn't matter, because the loop should always end. It's either getting `break`d or `count` is set to 0 and it will stop. Do you call `setNumber` from another loop? That could cause the infinity, if it's broken. – Bart van Heukelom Dec 07 '11 at 20:28
  • I do indeed call it from another class (which is a menu interface looping). – silverzx Dec 07 '11 at 21:44

7 Answers7

12

Unlike some languages (e.g. Ada), Java does not have a way to "predeclare" the acceptable range of a number. However, if you encapsulate the anumber into a class, you can enforce such a restriction using a setter method:

class RestrictedRangeExample {
    private int anumber;

    public void setAnumber(int newanumber) {
        if (newanumber >= 1 && newanumber <= 3) {
            anumber = newanumber;
        } else {
            throw new IllegalArgumentException("anumber out of range");
        }
    }
}
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
4
public void setAnumber(int value) {
    if ((value < 1) || (value > 3))
        throw new IllegalArgumentException("value is out of range for anumber");
    this.anumber = value;
}
duffymo
  • 305,152
  • 44
  • 369
  • 561
  • 3
    I would prefer the negated version `if ((1 <= value) && (value <= 3))`. More readable - the setting comes first, the exception in the `else` clause. – Yuval Adam Dec 07 '11 at 18:44
  • It's so much more readable that you got the comparison operator backwards. – Erick Robertson Dec 07 '11 at 18:58
  • I hope you mean Yuval; I think mine is right. I only throw the exception if the value fails to fall in the range. – duffymo Dec 07 '11 at 21:00
4

Enforcing the constraint inside the setter for this attribute would certainly work. Another thing you could do is use an enumeration instead of an integer, depending on the constraints of your homework assignment.

mongiesama
  • 355
  • 1
  • 3
  • 12
1

Unfortunately java.lang.Integer is final, so you cannot extend it. You can always implement class LimitedInteger and implement this logic there.

But It sounds like what you really need is enum supported by Java language since version 1.5.

AlexR
  • 114,158
  • 16
  • 130
  • 208
1

The only way you could achieve that is by definig your own class for the number you want to limit. But, based on my experience, it looks like to me that what you are looking for is not an integer with a limited range of values, but is actually an enum.

public enum MyNumber {
  ONE(1),
  TWO(2),
  THREE(3);

  private int value;

  private MyNumber(int value) {
    this.value = value;
  }

  public int getValue() {
    return value;
  }
}
loscuropresagio
  • 1,922
  • 15
  • 26
0

An Integer (int) does not have any constraints by itself, the only one are the minimum and maximum values bounded by the cardinality of a 32bit set. The method you are talking about is called an accessors. An accessor is a method which is used to set and get a value. This way you can validate, format or preprocess any value prior to assign them. You can easily code your accessor the following way:

import java.lang.Math.*;
void setNumber(int aNumber)
{
this.number = Math.min(3, Math.max(aNumber,1));
if (this.number != aNumber) throw new IllegalArgumentException("aNumber is out of range");
}

int getNumber()
{
return this.number;
}
Flavien Volken
  • 19,196
  • 12
  • 100
  • 133
-2

No, but you can use Range from Google Guava

korifey
  • 3,379
  • 17
  • 17