用java实现一个枚举类,通过编号(从1开始)得到30道菜肴
时间: 2023-05-27 19:05:52 浏览: 125
java枚举类用法
```
public enum Dishes {
// 枚举值
ROAST_DUCK(1, "烤鸭"),
BRAISED_PORK(2, "红烧肉"),
SPICY_CHICKEN(3, "辣子鸡"),
HOT_POT(4, "火锅"),
KUNG_PAO_CHICKEN(5, "宫保鸡丁"),
FRIED_RICE(6, "炒饭"),
BRAISED_FISH(7, "红烧鱼"),
STIR_FRIED_VEGETABLES(8, "炒青菜"),
DUMPLINGS(9, "饺子"),
NOODLES_WITH_SOY_SAUCE(10, "炒面"),
SWEET_AND_SOUR_PORK(11, "糖醋里脊"),
MAPO_TOFU(12, "麻婆豆腐"),
STEAMED_FISH(13, "清蒸鱼"),
CRISPY_FRIED_CHICKEN(14, "香酥鸡"),
BRAISED_BEEF_NOODLES(15, "红烧牛肉面"),
SPRING_ROLLS(16, "春卷"),
TOMATO_AND_EGG_STIR_FRY(17, "西红柿炒鸡蛋"),
COLD_NOODLES(18, "凉拌面"),
SPICY_FISH_HOT_POT(19, "麻辣鱼火锅"),
BEIJING_NOODLES(20, "炸酱面"),
BRAISED_PORK_KNUCKLES(21, "红烧猪蹄"),
SEAFOOD_NOODLES(22, "海鲜面"),
SAUTEED_BEEF_WITH_ONIONS(23, "洋葱炒牛肉"),
CRISPY_FRIED_TOFU(24, "炸豆腐"),
SWEET_AND_SOUR_FISH(25, "糖醋鱼"),
CHINESE_PIZZA(26, "煎饼果子"),
STIR_FRIED_EGGPLANT(27, "炒茄子"),
HOT_AND_SOUR_SOUP(28, "酸辣汤"),
ROAST_LAMB(29, "烤羊肉"),
SPICY_HOT_POT(30, "麻辣火锅");
// 编号和名称
private final int code;
private final String name;
// 构造函数
Dishes(int code, String name) {
this.code = code;
this.name = name;
}
// 通过编号获取菜肴名称
public static String getNameByCode(int code) {
for (Dishes dish : Dishes.values()) {
if (dish.code == code) {
return dish.name;
}
}
return null;
}
}
```
使用示例:
```
public class Test {
public static void main(String[] args) {
// 获取第1道菜肴名称
String dish1 = Dishes.getNameByCode(1);
System.out.println("第1道菜肴是:" + dish1);
// 获取第5道菜肴名称
String dish5 = Dishes.getNameByCode(5);
System.out.println("第5道菜肴是:" + dish5);
// 获取第30道菜肴名称
String dish30 = Dishes.getNameByCode(30);
System.out.println("第30道菜肴是:" + dish30);
}
}
```
阅读全文