/* * Author: Adriana Ferraro * Date: Semester 1, 2007 * Purpose: This program executes the exercises * in the lecture 18 slides */ public class TrafficLight { public static final int GREEN = 0; public static final int ORANGE = 1; public static final int RED = 0; private int showing; private int idNumber; public TrafficLight(int id) { idNumber = id; showing = (int)(Math.random() * 3); } public void setColour(int colourIndex) { showing = colourIndex % 3; } public void change() { showing++; showing = showing % 3; } public boolean equals(TrafficLight other) { if (showing == other.showing && idNumber == other.idNumber) { return true; } return false; } public boolean showsSameColour(TrafficLight other) { if (showing == other.showing) { return true; } return false; } public String toString() { String outS = ""; outS = "Traffic light: " + idNumber; outS = outS + ", showing: " + getColour(showing); return outS; } private String getColour(int index) { final String[] colours = {"GREEN", "ORANGE", "RED" }; return colours[index]; } //-------------------------------------------------- //-------------------------------------------------- public static void main(String[] args) { TrafficLight t1, t2; t1 = new TrafficLight(334); t2 = new TrafficLight(335); for( int i=0; i<5; i++) { t1.change(); System.out.println(i + " " + t1.toString()); } System.out.println(); for( int i=0; i<5; i++) { if(Math.random() < 0.5) { t1.change(); } if(Math.random() < 0.5) { t2.change(); } System.out.println("TIME: " + i); System.out.println(t1.toString()); System.out.println(t2.toString()); System.out.println("Same colour: " + t1.showsSameColour(t2)); System.out.println(); } } }