Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a range for an Integer in Java [duplicate]

Tags:

java

integer

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;
            }
    }
}
like image 393
silverzx Avatar asked Dec 07 '11 18:12

silverzx


2 Answers

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");
        }
    }
}
like image 98
Greg Hewgill Avatar answered Oct 04 '22 21:10

Greg Hewgill


public void setAnumber(int value) {
    if ((value < 1) || (value > 3))
        throw new IllegalArgumentException("value is out of range for anumber");
    this.anumber = value;
}
like image 28
duffymo Avatar answered Oct 04 '22 23:10

duffymo