tags:

views:

101

answers:

3

I am trying to think of an elegant way to solve this problem in Java:

Given an int of 0-100 what is an elegant way to turn it into an enum where each of the enum's possible values correspond to a range of ints.

For example

enum grades{

    A -> 90-95%
    B -> 85-90%,
    C -> 75-85%
    ...
    etc

}

Can anybody think of a concise way to write a method that given an int returns an enum of grades or throws a IllegalArgumentException?

+3  A: 

Write a static method, just like valueOf() is already there, call it say inRange(), return Grade.

public enum Grade {
    A(100, 90), B(89, 80), C(79, 70);

    int uBound;
    int lBound;

    Grade(int uBound, int lBound){
      ...
    }

    public static Grade inRange(int percent){
      ...
    }
}

Better initialize a static map, percent as keys and Grade as values. I suggest you to use apache commons collection's MapUtils in this case. Below is an example,

private static final Map<Integer, Grade> GRADE_MAP = UnmodifiableMap.decorate(
        MapUtils.putAll(new HashMap<Integer, Grade>(), new Object[][]{
            {0, F}, {1, F}, .....,
            .....
            .....
            {100, A}
        }));

then your method will look like below,

    public static Grade inRange(int percent){
      return GRADE_MAP.get(percent);
    }
Adeel Ansari
Should I just have a bunch of if else-if statements in the valueOf and inRange methods?
Benju
`switch` wouldn't suit here. `if-else` sounds better.
Adeel Ansari
Or better still initialize a static make percent as keys, Grade as values. I suggest you to use apache commons collection's `MapUtils` in this case.
Adeel Ansari
+1  A: 

I'd make the boundaries an attribute of the enum, and implement a method

public boolean isInRange(int i)

in the enum, using the boundary and the boundary of the enum with the next lower ordinal number.

Finally implement a static method on the enum, that iterates through the instances to find the matching instance.

Jens Schauder
+1  A: 

Ahead of time create an array with index 0..100 and assign each slot to the value you want it to correspond to.

Then in the actual loop just look the value up in the array.

Thorbjørn Ravn Andersen
Thanks, your idea has been adopted, in a slightly different way.
Adeel Ansari