#Training Traffic Light
We are going to program traffic lights (popularly known as stop lights). Now it’s a pretty straightforward variant, but after theory in later chapters it will be extended. So save the code you create!
Before we start typing code we always think about what we want to achieve:
objects
of type TrafficLight, but I only want to program it once.green',
orange’, `red’: use English names for these states.Console
project to named Traffic.class
TrafficLight.private
Field
color of type String.method
NextState() that gives the TrafficLight the next value of color.public String GetCurrentColor()
method
NextState returns the color after changing the color: public String NextState() {...}
A Console app has a mainmethod (public static void Main(string [] args)
)
in which you can put code like:
TrafficLight trafficLight = new TrafficLight();
// color has to be "Red".
Console.WriteLine(trafficLight.GetCurrentcolor());
trafficLight.NextState();
// color has to be "green".
Console.WriteLine(trafficLight.GetCurrentColor());
trafficLight.NextState();
// color has to be "orange".
Console.WriteLine(trafficLight.GetCurentColor());
trafficLight.NextState();
// and 'red' again!
Console.WriteLine(trafficLight.GetCurentColor());
The above code is somewhat sloppily put together: check for errors! Correct them if necessary and test the program. Can you think of any improvements to the program?