Java Data Type How to - Set the value of an enum by user input








Question

We would like to know how to set the value of an enum by user input.

Answer

//from  w  w  w .ja  v  a 2 s.c  om
import java.util.HashMap;
import java.util.Map;

enum Value {
  A(1), B(2), C(3), D(4), E(5), F(6), G(7), H(8), I(9), J(10), K(11);

  private int numericValue;
  private static final Map<Integer, Value> intToEnum = new HashMap<Integer, Value>();
  static {
    for (Value type : values()) {
      intToEnum.put(type.getNumericValue(), type);
    }
  }

  private Value(int numericValue) {
    this.numericValue = numericValue;
  }

  public int getNumericValue() {
    return this.numericValue;
  }

  public static Value fromInteger(int numericValue) {
    return intToEnum.get(numericValue);
  }
};

public class Main {
  public static void main(String[] args) {
    Value choice;
    for (Value value : Value.values()) {
      System.out.println(value.getNumericValue() + " : " + value);
    }

    choice = Value.fromInteger(2);
    if (choice == null) {
      System.out.println("Please select a valid class");
    }
  }
}

The code above generates the following result.