「Java」列挙型(enum)の基本的な使い方とサンプルコード

書式
enum 列挙名{}
列挙名.メンバー
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study.tm;
public class EnumUseDemo {
//列挙UserCode
enum UserCode {
KA(0),
KB(1),
KC(2);
int value;
UserCode(int value) {
this.value = value;
}
}
public static void main(String[] args) {
int a = 2;
//関数testFuncを呼び出す
testFunc(a);
}
//関数testFuncの定義
public static void testFunc(int n) {
if (n == UserCode.KA.value) {
System.out.println("message AA01");
} else if (n == UserCode.KB.value) {
System.out.println("message BB02");
} else if (n == UserCode.KC.value) {
System.out.println("message CC03");
}
}
}
package com.arkgame.study.tm; public class EnumUseDemo { //列挙UserCode enum UserCode { KA(0), KB(1), KC(2); int value; UserCode(int value) { this.value = value; } } public static void main(String[] args) { int a = 2; //関数testFuncを呼び出す testFunc(a); } //関数testFuncの定義 public static void testFunc(int n) { if (n == UserCode.KA.value) { System.out.println("message AA01"); } else if (n == UserCode.KB.value) { System.out.println("message BB02"); } else if (n == UserCode.KC.value) { System.out.println("message CC03"); } } }
package com.arkgame.study.tm;

public class EnumUseDemo {

      //列挙UserCode
      enum UserCode {
            KA(0),
            KB(1),
            KC(2);
            int value;

            UserCode(int value) {
                  this.value = value;
            }
      }

      public static void main(String[] args) {
            int a = 2;
            //関数testFuncを呼び出す
            testFunc(a);
      }
      //関数testFuncの定義
      public static void testFunc(int n) {
            if (n == UserCode.KA.value) {
                  System.out.println("message AA01");
            } else if (n == UserCode.KB.value) {
                  System.out.println("message BB02");

            } else if (n == UserCode.KC.value) {
                  System.out.println("message CC03");
            }

      }
}

実行結果
message CC03

Java

Posted by arkgame