枚举类代替 ifelse
时间: 2023-11-03 07:06:59 浏览: 228
使用JS枚举简化if else
枚举类可以用来代替 ifelse 语句,可以提高代码的可读性和可维护性。枚举类可以定义一组常量,每个常量都有一个对应的值,可以通过枚举类来判断变量的取值,从而避免使用 ifelse 语句。
例如,我们可以定义一个枚举类来表示一周的天数:
```
public enum DayOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
```
然后可以使用 switch 语句来判断变量的取值:
```
DayOfWeek day = DayOfWeek.MONDAY;
switch (day) {
case MONDAY:
System.out.println("Today is Monday");
break;
case TUESDAY:
System.out.println("Today is Tuesday");
break;
case WEDNESDAY:
System.out.println("Today is Wednesday");
break;
case THURSDAY:
System.out.println("Today is Thursday");
break;
case FRIDAY:
System.out.println("Today is Friday");
break;
case SATURDAY:
System.out.println("Today is Saturday");
break;
case SUNDAY:
System.out.println("Today is Sunday");
break;
}
```
这样就可以避免使用 ifelse 语句来判断变量的取值。
阅读全文