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 非法时,我如何确保收到错误消息?

4

5 回答 5

0

我在本地对此进行了测试,并正确打印了错误消息。

PawnColor ratingFor = PawnColor.illegal;
if(ratingFor == PawnColor.illegal)
{
    System.out.println("Something has gone wrong.");
}
于 2012-12-04T18:26:34.710 回答
0

它应该是:

if (ratingFor == illegal)
于 2012-12-04T18:27:15.547 回答
0
if(ratingFor.equals(illegal)) {
    System.out.println("Something has gone wrong.");
}

这里不能引用“非法”,ratingFor 只能比作PawnColor.class 类型。

ratingFor == PawnColor.illegal 

或者

ratingFor.equals(PawnColor.illegal)

会给你想要的结果

于 2012-12-05T05:53:30.613 回答
0

对于枚举常量,equals 和 == 表示相同的内容,并且可以互换使用

于 2012-12-04T18:31:00.620 回答
0

您需要引用illegalPawnColor.illegal.

只需==用作:

   if(ratingFor == PawnColor.illegal)

您还可以equals用作:

   if(PawnColor.illegal.equals(ratingFor))
于 2012-12-04T18:27:44.470 回答