1. はじめに
- JavaでEnumのメソッドを使ってみたい
2. 開発環境
- java
3. サンプルコード
// Enumの定義
public enum enumMonth {
October("A", "10"), November("B", "11"), December("B", "12");
// フィールドを定義
private String code;
private String value;
// コンストラクタを定義
private enumMonth(String pCode, String pValue) {
this.code = pCode;
this.value = pValue;
}
// メソッド
public static String getValueByCode(String pId) {
for (enumMonth month : enumMonth.values()) {
if (month.code.equals(pId)) {
return month.value;
}
}
return "0" + pId.substring(0, 1);
}
}
4. 実行サンプル
// Enumのテスト
String month_0 = enumMonth.getValueByCode("0");
String month_1 = enumMonth.getValueByCode("1");
String month_2 = enumMonth.getValueByCode("2");
String month_3 = enumMonth.getValueByCode("3");
String month_4 = enumMonth.getValueByCode("4");
String month_5 = enumMonth.getValueByCode("5");
String month_6 = enumMonth.getValueByCode("6");
String month_7 = enumMonth.getValueByCode("7");
String month_8 = enumMonth.getValueByCode("8");
String month_9 = enumMonth.getValueByCode("9");
String month_A = enumMonth.getValueByCode("A");
String month_B = enumMonth.getValueByCode("B");
String month_C = enumMonth.getValueByCode("C");
System.out.println("0:" + month_0);
System.out.println("1:" + month_1);
System.out.println("2:" + month_2);
System.out.println("3:" + month_3);
System.out.println("4:" + month_4);
System.out.println("5:" + month_5);
System.out.println("6:" + month_6);
System.out.println("7:" + month_7);
System.out.println("8:" + month_8);
System.out.println("9:" + month_9);
System.out.println("A:" + month_A);
System.out.println("B:" + month_B);
System.out.println("C:" + month_C);
System.out.println("0:" + month_0);