用java实现一个枚举类,通过编号(从1开始)得到10个常见的动物名
时间: 2023-05-27 08:05:41 浏览: 87
Java面向对象(高级)- 枚举类的使用
public enum AnimalEnum {
DOG(1, "狗"),
CAT(2, "猫"),
PIG(3, "猪"),
COW(4, "牛"),
SHEEP(5, "羊"),
HORSE(6, "马"),
ELEPHANT(7, "大象"),
LION(8, "狮子"),
TIGER(9, "老虎"),
MONKEY(10, "猴子");
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 animalEnum : AnimalEnum.values()) {
if (animalEnum.getCode() == code) {
return animalEnum.getName();
}
}
return null;
}
}
// 调用
String animalName = AnimalEnum.getNameByCode(1); // animalName = "狗"
阅读全文