選ばれた動物の鳴き声を表示 (列挙体)

明解C言語 入門編 > 8. いろいろなプログラムを作ってみよう >

選ばれた動物の鳴き声を表示 (列挙体)

Java
import java.util.Scanner;

class Lesson062 {
    enum animal {
        Dog(0), Cat(1), Monkey(2), Invalid(3);
        private int value;

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

        // enum定数から整数へ変換
        int getIntValue() {
            return this.value;
        }

        // 整数からenum定数へ変換
        static animal valueOf(final int value) {
            for (animal d : values()) {
                if (d.getIntValue() == value) {
                    return d;
                }
            }
            return null;
        }
    }

    public static void main(String[] args) {
        animal selected;

        do {
            switch (selected = select()) {
                case Dog:    dog();    break;
                case Cat:    cat();    break;
                case Monkey: monkey(); break;
            }
        } while (selected.getIntValue() < animal.Invalid.getIntValue());
    }

    static animal select() {
        Scanner stdIn = new Scanner(System.in);
        int tmp;
        do {
            System.out.printf("0…犬  1…猫  2…猿  3…終了");
            tmp = stdIn.nextInt();
        } while (tmp < animal.Dog.getIntValue() || tmp > animal.Invalid.getIntValue());

        return animal.valueOf(tmp);
    }

    static void dog() {
        System.out.println("ワンワン!!");
    }
    static void cat() {
        System.out.println("ニャ〜オ!!");
    }
    static void monkey() {
        System.out.println("キッキッ!!");
    }
}

実行結果

L:\>java Lesson062
0…犬 1…猫 2…猿 3…終了0
ワンワン!!
0…犬 1…猫 2…猿 3…終了1
ニャ〜オ!!
0…犬 1…猫 2…猿 3…終了2
キッキッ!!
0…犬 1…猫 2…猿 3…終了9
0…犬 1…猫 2…猿 3…終了3