Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 3 ■ DATA TYPES

Listing 3-15. findCardinalDirection method


public static Direction findCardinalDirection (int degrees) {
if (degrees < 45) {
return NORTH;
} else if (degrees < 135) {
return EAST;
} else if (degrees < 225) {
return SOUTH;
} else if (degrees < 315) {
return WEST;
} else {
return NORTH;
}
}


You might also notice the different syntax for iterating through a for loop. That syntax is not unique
to enumerations, but it is especially handy for them. We cover these alternate ways of using a for loop
when we get to looping in a later chapter.
As you can see, an enumeration is far more powerful than a simple list of constants. It's also safer,
because no one can confuse Direction.North with 0.
Listing 3-16 shows the full code for the Direction enumeration.


Listing 3-16. Complete enumeration example


package com.bryantcs.examples.enumExample;


public enum Direction {
NORTH (0),
EAST (90),
SOUTH (180),
WEST (270);


private final int degrees;
Direction(int degrees) {
this.degrees = degrees;
}


public int getDegrees() {
return degrees;
}


// static because it doesn't rely on a particular direction
public static Direction findCardinalDirection (int degrees) {
if (degrees < 45) {
return NORTH;
} else if (degrees < 135) {
return EAST;
} else if (degrees < 225) {
return SOUTH;
} else if (degrees < 315) {
return WEST;

Free download pdf