用java实现一个枚举类,通过编号(从1开始)得到20个常见的动物名
时间: 2023-05-27 15:05:41 浏览: 192
public enum AnimalEnum {
DOG(1, "狗"),
CAT(2, "猫"),
LION(3, "狮子"),
TIGER(4, "老虎"),
ELEPHANT(5, "大象"),
PANDA(6, "熊猫"),
MONKEY(7, "猴子"),
BEAR(8, "熊"),
DEER(9, "鹿"),
ANTELOPE(10, "羚羊"),
HORSE(11, "马"),
COW(12, "牛"),
SHEEP(13, "羊"),
GOAT(14, "山羊"),
RABBIT(15, "兔子"),
FOX(16, "狐狸"),
WOLF(17, "狼"),
BEAVER(18, "海狸"),
OTTER(19, "水獭"),
SQUIRREL(20, "松鼠");
private int code;
private String name;
AnimalEnum(int code, String name) {
this.code = code;
this.name = name;
}
public int getCode() {
return code;
}
public String getName() {
return name;
}
public static String getNameByCode(int code) {
for (AnimalEnum animal : AnimalEnum.values()) {
if (animal.getCode() == code) {
return animal.getName();
}
}
return null;
}
}
阅读全文