首页javaenumJava Data Type - 如何通过用户输入设置枚举的值

Java Data Type - 如何通过用户输入设置枚举的值

我们想知道如何通过用户输入设置枚举的值。
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");
    }
  }
}