2012-12-04 50 views
0

我有一個名爲PawnColor一個枚舉,它只是包含以下內容:如何比較兩個枚舉?

public enum PawnColor { 
    black, white, none, illegal 
} 

如果我有下面的方法,我怎麼能檢查PawnColor當前實例的顏色?

public double ratePosition (PawnColor ratingFor) { 
    // ... 
} 

所以,如果ratingFor有顏色:illegal,我怎麼可能去檢查呢?我從來沒有使用枚舉工作之前,我有氣無力地試圖做:

if(ratingFor.equals(illegal)) { 
    System.out.println("Something has gone wrong."); 
} 

它沒有明顯的工作,我將如何確保我得到一個錯誤消息時PawnColor ratingFor是非法的?

+2

爲什麼不讀枚舉的教程?有很多,你可以節省自己的時間,從長遠來看... – NPE

+0

我嘗試了一個看起來很簡單,因爲它很簡單,但它根本無法工作:http://stackoverflow.com/questions/6875677/最好的方式比較枚舉?rq = 1 –

+0

@MattAndrzejczuk你得到了什麼?例外?沒有錯誤信息? – bellum

回答

0

我在本地進行了測試,錯誤信息打印正確。

PawnColor ratingFor = PawnColor.illegal; 
if(ratingFor == PawnColor.illegal) 
{ 
    System.out.println("Something has gone wrong."); 
} 
0

它應該是:

if (ratingFor == illegal) 
0

您需要參考illegalPawnColor.illegal

只需使用==爲:

if(ratingFor == PawnColor.illegal) 

你也可以使用equals爲:

if(PawnColor.illegal.equals(ratingFor)) 
0

,枚舉常量,等於和==量,同樣的事情,並且可以互換使用

0
if(ratingFor.equals(illegal)) { 
    System.out.println("Something has gone wrong."); 
} 

在這裏你不能引用「非法」,ratingFor只能比較類型PawnColor.class。

ratingFor == PawnColor.illegal 

ratingFor.equals(PawnColor.illegal) 

會給你想要的結果