enum和switch case结合使用

简介: 在将enum和switch case结合使用的过程中,遇到了这个错误:“An enum switch case label must be the unqualified name of an enumeration constant”。

enum和switch case结合使用

在将enum和switch case结合使用的过程中,遇到了这个错误:“An enum switch case label must be the unqualified name of an enumeration constant”,代码如下所示:

public enum EnumType {
    type1("type1"), type2("type2"), type3("type3");
    private String type;

    EnumType(String type) {
        this.type = type;
    }

    public String getType() {
        return type;
    }
}

@OnClick(R.id.btn_test_enum_with_switchcase)
public void onViewEnumWithSwitchCaseClicked() {
    EnumType enumType = EnumType.type1;
    testEnum(enumType);
}

private void testEnum(EnumType type) {
    switch (type) {
        case EnumType.type1:
            Log.e("type1:", type.getType());
            break;
        case EnumType.type2:
            Log.e("type2:", type.getType());
            break;
        case EnumType.type3:
            Log.e("type3:", type.getType());
            break;
        default:
            break;
    }
}

错误提示如下所示:An enum switch case label must be the unqualified name of an enumeration constant
这里写图片描述

根据错误提示的意思,枚举类型和switch case一起使用时一定不要限定枚举常量值的常量,也就是它的类型。
对代码做下修改:

private void testEnum(EnumType type) {
    switch (type) {
        case type1:
            Log.e("type1:", type.getType());
            break;
        case type2:
            Log.e("type2:", type.getType());
            break;
        case type3:
            Log.e("type3:", type.getType());
            break;
        default:
            break;
    }
}

好了,修改完成。

相关文章
|
8月前
|
Java 编译器 C语言
【C/C++】 switch-case 详解/全面总结
关于 C语言/C++ 中,switch-case 的尽量详细和全面的解释与总结
450 0
switch case 执行
switch case 执行
93 0
|
C#
switch case语句
switch case语句
127 0
|
Dart
Dart之break、continue/ switch...case
Dart之break、continue/ switch...case
77 0
Dart之break、continue/ switch...case
switch—case需要注意的点
switch—case需要注意的点
169 0
switch—case需要注意的点
|
Java 开发者
switch case 支持的 6 种数据类型!
有粉丝建议可以偶尔推送一些 Java 方面的基础知识,一方面可以帮助一初学者,也可以兼顾中高级的开发者。 那么今天就讲一下 Java 中的 switch case 语句吧,有忘记的同学正好可以温习一下。 Java 中 switch case 语句用来判断一个变量与一系列值中某个值是否相等,每个值称为一个分支。
147 0
|
网络虚拟化 数据安全/隐私保护 iOS开发