switch判断中使用枚举进行判断

时间:2025-02-21 10:31:49

目录

文章目录

一、switch中使用枚举进行判断处理

二、使用步骤

1.枚举类中添加获取某个枚举的方法

判断的写法

An enum switch case label must be the unqualified name of an enumeration constant

一、switch中使用枚举进行判断处理

在switch中不能直接使用枚举类中的某个属性进行判断,可以在枚举类中添加获取枚举的一个方法,然后根据传入的参数获取满足条件的枚举,然后使用这个枚举进行判断

二、使用步骤

1.枚举类中添加获取某个枚举的方法

代码如下:

package enun;


public enum TypeEnum {
    TYPE_ONE(1, "你好"),
    TYPE_TWO(2, "再见");

    public final Integer type;
    public final String name;

    TypeEnum(Integer type, String name) {
         = type;
         = name;
    }

    public static TypeEnum getByCode(Integer type) {
        for(TypeEnum e : ()){
            if((type)){
                return e;
            }
        }
        return null;
    }
}

判断的写法

代码如下:

package ;

import ;

/**
 * @author linaibo
 * @version 1.0
 * Create by 2022/8/20 14:04
 */

public class enumTest {
    public static void main(String[] args) {
        int a = 2;
        switch ((a)){
            case TYPE_ONE:
                ("成功1");
                ();
                break;
            case TYPE_TWO:
                ("成功2");
                break;
            default:
                ("失败");
        }
        (TypeEnum.TYPE_ONE.name);

    }
}

通过传入的某个枚举的type属性来获得这个枚举类,注意case后面直接使用枚举类中的枚举对象进行判断,不需要加上枚举类的名字,加上之后会报下面的错误

An enum switch case label must be the unqualified name of an enumeration constant