使用枚举类enum代替switch
使用枚举类,能大大减少switch的代码量,提高代码阅读性
public enum TestEnum {
stu1("小明", "一班"),
stu2("小红", "二班"),
stu3("小丽", "一班"),
stu4("小刚", "三班"),
stu5("小敏", "一班"),
stu6("小帅", "二班");
private String name;
private String banji;
TestEnum() {
}
TestEnum(String name, String banji) {
this.name = name;
this.banji = banji;
}
//根据姓名获取所在班级
public static String getByName(String value) {
for (TestEnum testEnum : values()) {
if (testEnum.getName().equals(value)) {
return testEnum.getBanji();
}
}
return null;
}
public String getName() {
return name;
}
public String getBanji() {
return banji;
}
}
class Test {
//用法
public static void main(String[] args) {
System.out.println(TestEnum.getByName("小红"));
}
}