无法访问Switch Case / Java中的枚举值

时间:2014-02-18 11:24:59

标签: java enums switch-statement

我无法在switch-case语句中访问我的枚举变量:

public enum Country {

FRANCE(0, "France"), SPAIN(1, "Spain");
private final int code;
private final String name;
Country(int code, String name) {
    // TODO Auto-generated constructor stub
    this.code = code;
    this.name = name;
}
public int getCode() {
    return code;
}
public String getName() {
    return name;
}
}

在另一个课程中有以下代码:

public Drawable getFlag(){
    Drawable d = null;
    switch(country_id){
    case Country.FRANCE.getCode():
        break;
    }
    return d;
}

但问题是当我输入国家时,只有一个类或者这个。

3 个答案:

答案 0 :(得分:2)

case语句中的

switch标签需要是常量

答案 1 :(得分:2)

case语句中的表达式必须是常量值。 解决问题的一种(常用)方法是创建一个从数字代码中获取枚举的函数:

public enum Country {
...
public static Country getCountry(int countryCode) {
    for(Country country : Country.values()) {
        if(country.code == countryCode) {
            return country;
        }
    }
    throw new IllegalArgumentException();
}

然后你就可以对枚举进行切换了:

switch(Country.getCountry(country_id)){
case Country.FRANCE:
    break;
...
}

答案 2 :(得分:1)

case表达式必须是编译时常量表达式。你的枚举实例的变量是常量,但不是编译时常量。

  

我们调用一个原始类型或类型String的变量,这是最终的   并使用编译时常量表达式(第15.28节)初始化a   常数变量。变量是否是常量变量   可能对类初始化有影响(第12.4.1节),   二进制兼容性(§13.1,§13.4.9)和明确赋值(§16)。

相关问题