【Java常用类之enumm枚举类 20】

一、枚举,避免代码错误发生在运行期,尽量在编译时就发现错误

举例:例一:不用枚举  例二:用枚举   通过对比来发现枚举的好处

例1:

package com.JavaStudy.wrapperEnumm0622;

/**
 * @Author wufq
 * @Date 2020/6/22 10:16
 * 不用枚举的例子
 */
public class EnummTest01 {


    public static void main(String[] args){
        int a = 10;
        int b = 1;

        int retValue = divide(a,b);

        //判断条件写错的话,只有在运行时才能发现
        if(retValue == 1){
            System.out.println("成功");
        }else if(retValue ==0){
            System.out.println("失败");
        }
    }

    public static int divide(int a,int b){

        try {
             int c =a/b;
            return 1;
        } catch (Exception e) {
            return 0;
        }
    }
}

例2:

package com.JavaStudy.wrapperEnumm0622;

/**
 * @Author wufq
 * @Date 2020/6/22 10:17
 * 使用枚举: 避免错误发生在运行期
 */
public class EnummTest02 {
    public static void main(String[] args){
        int a = 10;
        int b = 1;

        Result retValue = divide(a,b);

        //用了枚举,就可以在写代码时发现错误
        if(retValue == Result.SUCCESS){
            System.out.println("成功");
        }else if(retValue == Result.FAIL){
            System.out.println("失败");
        }

    }
    //重点注意静态方法的数据类型用的是枚举类
    public static Result divide(int a,int b){

        try {
            int c = a/b;
            return Result.SUCCESS;
        } catch (Exception e) {
            return Result.FAIL;
        }
    }


}
//定义一个枚举类
enum Result{
    //规范要求:大写
    SUCCESS,FAIL;
}

//四季  -->一个枚举类可以写多个值,规范要求大写
enum Season{
    SPRING,SUMMER,AUTUMN,WINTER;
}

//颜色
enum Color{
    BLUE,GREEN,RED;
}
原文地址:https://www.cnblogs.com/frankruby/p/13175678.html