用java实现一个枚举类,通过编号得到湖南省的所有的地级市
时间: 2023-05-29 07:02:41 浏览: 103
基于java枚举类综合应用的说明
public enum HunanCity {
CHANGSHA(1, "长沙市"),
ZHUZHOU(2, "株洲市"),
XIANGTAN(3, "湘潭市"),
HENGYANG(4, "衡阳市"),
YUEYANG(5, "岳阳市"),
CHANGDE(6, "常德市"),
ZHANGJIAJIE(7, "张家界市"),
YIYANG(8, "益阳市"),
CHENZHOU(9, "郴州市"),
YONGZHOU(10, "永州市"),
HUAIHUA(11, "怀化市"),
LOUDI(12, "娄底市"),
XIAOYI(13, "湘西土家族苗族自治州");
private int number;
private String name;
HunanCity(int number, String name) {
this.number = number;
this.name = name;
}
// 根据编号获取地级市名称
public static String getNameByNumber(int number) {
for (HunanCity city : HunanCity.values()) {
if (city.number == number) {
return city.name;
}
}
return null;
}
}
// 测试
public class Main {
public static void main(String[] args) {
System.out.println(HunanCity.getNameByNumber(1)); // 输出:长沙市
System.out.println(HunanCity.getNameByNumber(2)); // 输出:株洲市
}
}
阅读全文