public class Lab10sol { public static void main(String[] args) { TrafficSignal ts = new TrafficSignal(); // create a new TrafficSignal ts.runOneCycle(); // run one cycle of the Bulbs System.out.println(ts); // output how much time the cycle used } } // Class Lab10sol class TrafficSignal { private Bulb red = new Bulb("R", 120); // create red light Bulb private Bulb green = new Bulb("G", 120); // create green light Bulb private int time; // amount of time used in one cycle // Activate the red and green Bulbs in succession: public void runOneCycle() { red.runLight(); // run the red Bulb time += red.getTime(); // add the amount of time from red green.runLight(); // run the green Bulb time += green.getTime(); // add the amount of time from green } // Return a String description of how much time the TrafficSignal has run: public String toString() { return "The traffic signal ran for "+time+" secs."; } } // Class TrafficSignal class Bulb { private String color; // color of the light Bulb private int duration; // amount of time light Bulb designed to stay on (sec) private boolean on; // whether or not Bulb is on: $true$ means on private int time; // amount of time Bulb has been on (sec) // Create a new Bulb with color and duration: public Bulb(String color, int duration) { this.color = color; // set color of Bulb this.duration = duration ; // set duration of Bulb } // Return the amount of time that the Bulb was on: public int getTime() { return time; } // Turn the current Bulb off and on: private void turnOff() { on=false ; } private void turnOn() { on=true ; } // Run the current Bulb for the duration of time, after which the Bulb will turn // off. During the operation, the Bulb may randomly turn off after 30 seconds: public void runLight() { turnOn(); // turn Bulb on time = 30; // Bulb stays on at least 30 sec // Operate Bulb for remainder of duration. Has 1% chance of shutting off // at beginning or end of a second: shutOffAtRandom(); while (on && time < duration) { time++; shutOffAtRandom(); } turnOff(); // Bulb shuts off after duration is over } // Turn the Bulb off about 1% of the time: private void shutOffAtRandom() { if (MyMath.myRandom(1,100)==1) turnOff(); } } // Class Bulb class MyMath { public static int myRandom(int low, int high) { return (int) (Math.random()*(high-low+1)) + (int) low; } }