Java Reference
In-Depth Information
Try This 12-1 A Computer-Controlled Traffic Light
Enumerations are particularly useful when your program needs a set of constants, but the
actual values of the constants are arbitrary, as long as all differ. This type of situation comes
up quite often when programming. One common instance involves handling the states in
which some device can exist. For example, imagine that you are writing a program that
controls a traffic light. Your traffic light code must automatically cycle through the light's
three states: green, yellow, and red. It also must enable other code to know the current color
of the light and let the color of the light be set to a known initial value. This means that the
three states must be represented in some way. Although it would be possible to represent
these three states by integer values (for example, the values 1, 2, and 3) or by strings (such
as "red", "green", and "yellow"), an enumeration offers a much better approach. Using an
enumeration results in code that is more efficient than if strings represented the states and
more structured than if integers represented the states.
In this project, you will create a simulation of an automated traffic light, as just de-
scribed. This project not only demonstrates an enumeration in action, it also shows another
example of multithreading and synchronization.
1 . Create a file called TrafficLightDemo.java .
2 . Begin by defining an enumeration called TrafficLightColor that represents the three
states of the light, as shown here:
 
Search WWH ::




Custom Search