2014-02-18 51 views
1

我不能訪問我的switch-case語句我枚舉變量:無法訪問枚舉值開關罩內/ Java的

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; 
} 

但問題是,當我輸入國家,只有班或這。

回答

1

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

case標籤在switch聲明無需是常數

1

的情況下表達必須是編譯時間常數表達式。你的枚舉實例的變量是常量,但不是編譯時間常量。

我們稱一個變量,原始類型或String類型的,也就是最終 ,並用一個編譯時間常量表達式(§15.28)一個 常量變量初始化。變量是否爲常量變量 可能對類初始化(§12.4.1), 二進制兼容性(§13.1,§13.4.9)和明確賦值(§16)有影響。