0

I have an enum named PawnColor which simply contains the following:

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

If I had the following method, how could I check the color of the current instance of PawnColor?

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

So if ratingFor had the color: illegal, how could I go about checking this? I've never worked with enums before, I feebly tried doing:

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

It didn't work obviously, how would I make sure that I get an error message when PawnColor ratingFor is illegal?

Perception
  • 79,279
  • 19
  • 185
  • 195
Matt Andrzejczuk
  • 2,001
  • 9
  • 36
  • 51
  • 2
    Why not just read a tutorial on enums? There are plenty, and you'll save yourself time in the long run... – NPE Dec 04 '12 at 18:29
  • I tried one that looked as easy as it was simple but it did not work at all: http://stackoverflow.com/questions/6875677/the-best-way-to-compare-enums?rq=1 – Matt Andrzejczuk Dec 04 '12 at 18:52
  • @MattAndrzejczuk what did you get? exception? no error message? – bellum Dec 04 '12 at 19:06

5 Answers5

0

I tested this locally and error message is printed correctly.

PawnColor ratingFor = PawnColor.illegal;
if(ratingFor == PawnColor.illegal)
{
    System.out.println("Something has gone wrong.");
}
bellum
  • 3,642
  • 1
  • 17
  • 22
0

It should be:

if (ratingFor == illegal)
sampson-chen
  • 45,805
  • 12
  • 84
  • 81
0

You need to refer illegal as PawnColor.illegal.

Simply use == as :

   if(ratingFor == PawnColor.illegal)

You may also use equals as:

   if(PawnColor.illegal.equals(ratingFor))
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
0

For enum constants, equals and == amount to the same thing, and can be used interchangeably

Sergii Zagriichuk
  • 5,389
  • 5
  • 28
  • 45
0
if(ratingFor.equals(illegal)) {
    System.out.println("Something has gone wrong.");
}

Here you can not reference "illegal", ratingFor can only be compared to type PawnColor.class.

ratingFor == PawnColor.illegal 

or

ratingFor.equals(PawnColor.illegal)

will give you the desired result

Rahul
  • 15,979
  • 4
  • 42
  • 63