Can you define a variable in ranges in java

71 views Asked by At

When using variables can you define or specify that variable as all the numbers within a range like 1-10? I am using Switch statements and want to assign one of the case variables all the variables between 100-1000 without writing 900 case lines.

1

There are 1 answers

0
John Bayko On

If you want to use a switch statement for ranges, generally you need to map the ranges to specific values. They could be discrete integers, but in Java it makes sense to use enums, because the enum definition can have a method that does the mapping.

enums can be public, but they can also be private, within a class, if you don't need to use them anywhere else.

For example:

public class Something {
    private static enum RangeType {
        LOW(0, 10),
        MID(10, 20),
        HIGH(20, 30);

        private final int lowRange;
        private final int highRange;

        RangeType(int lowRange, int highRange) {
            this.lowRange = lowRange;
            this.highRange = highRange;
        }

        public RangeType getRange(int val) {
            for (RangeType rt : RangeType.values()) {
                if (rt.lowRange <= val && val < rt.highRange) {
                    return rt;
                }
            }
            return null;
        }
    }

    public int doSomething(int s) {
        int newS;

        RangeType sRange = RangeType.getRange(s);
        switch (sRange) {
        case LOW:
            newS = 15;
            break;
        case MID:
            newS = 3;
            break;
        case HIGH:
            newS = 9;
            break;
        default:
            newS = 0;
        }
        return newS;
    }

}

Using an enum might be overkill, but it does illustrate how the mapping can be done.