枚举enum
/*
1.枚举是一种引用数据类型
2.枚举语法:
enum 枚举类型名{
枚举值1,枚举值2
}
3.结果只有两种情况建议使用布尔类型,
结果大于两种情况建议使用枚举类型。例如:颜色、四季、星期
*/
public class EnumTest {
public static void main(String[] args) {
/*int divide = divide(10, 0);
System.out.println(divide == 1 ? "计算成功" : "计算失败");*/
Result divide = divide(10, 0);
System.out.println(divide == Result.SUCCESS ? "计算成功" : "计算失败");
}
//不使用枚举
/*public static int divide(int a, int b){
try {
int c = a / b;
return 1;
} catch (Exception exception) {
return 0;
}
}*/
/**
* 除法运算
* @param a int数据
* @param b int数据
* @return Result.SUCCESS 成功, Result.FAIL 失败
*/
//使用枚举
public static Result divide(int a, int b){
try {
int c = a / b;
return Result.SUCCESS;
} catch (Exception exception) {
return Result.FAIL;
}
}
}
enum Result {
SUCCESS,FAIL
}
switch与enum
public class SwitchEnumTest {
public static void main(String[] args) {
/*
1.switch 语句支持枚举类型
2.switch 也支持String、int
3.低版本的jdk,只支持int
4.高版本的jdk,支持int、String、枚举
5.byte short char也可以,因为存在自动类型转换
*/
switch (Season.SPRING){
case SPRING:
System.out.println("春天");
break;
case SUMMER:
System.out.println("夏天");
break;
case AUTUMN:
System.out.println("秋天");
break;
case WINTER:
System.out.println("冬天");
break;
}
}
}
enum Season{
SPRING, SUMMER, AUTUMN, WINTER
}