枚举类中根据key值获取value的方式
动物枚举类(AnimalEnum类)
package com.zxg.design_pattern.strategy.demo4;
public enum AnimalEnum {
DOG(1,"哮天犬"),
CAT(2,"大脸猫"),
DUCK(3,"可达鸭"),
RAT(4,"米老鼠"),
TIGER(5,"跳跳虎");
private final Integer key;
private final String value;
public Integer getKey() {
return key;
}
public String getValue() {
return value;
}
AnimalEnum(Integer key, String value) {
this.key = key;
this.value = value;
}
public static String getValueByKey(Integer code) {
AnimalEnum[] animalEnums = values();
for (AnimalEnum animal: animalEnums) {
if (animal.getKey().equals(code)) {
return animal.getValue();
}
}
return null;
}
}
测试类(Client4类)
package com.zxg.design_pattern.strategy.demo4;
import java.util.Scanner;
public class Client4 {
public static void main(String[] args) {
System.out.println("请输入1 - 5 中的其中一个数字:\n");
Scanner sc = new Scanner(System.in);
String str = sc.next();
String animalName = AnimalEnum.getValueByKey(Integer.valueOf(str));
System.out.println("该号码对应的动物是:" + animalName);
}
}
测试结果:
![在这里插入图片描述](https://img-blog.csdnimg.cn/83366b5ec55b4e168465138b44f49faf.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5rWF5rGQeg==,size_20,color_FFFFFF,t_70,g_se,x_16)