In: Computer Science
Create a system to simulate vehicles at an intersection. Assume that there is one lane going in each of four directions, with stoplights facing each direction. Vary the arrival average of vehicles in each direction and the frequency of the light changes to view the “behavior” of the intersection.
Answer : Given data
* Assume that there is one lane going in each of four directions, with stoplights facing each direction.
//Sample output
//Project structure
//Code to copy
package simulateVehicles;
public class VehiclesInQueue {
int vehicleNumber;
String typeOfVehicle;
/*Implementation of toString method */
public String toString(){
return vehicleNumber +" " +typeOfVehicle;
}
}
package simulateVehicles;
public class Lane {
VehiclesInQueue vehiclesList[];
int front,rear;
/*Implementation of Default constructor */
Lane(){
vehiclesList = null;
front = 0;
rear = 0;
}
/*Implementation of Parameterized constructor */
Lane(int sizeofQueue){
vehiclesList = new VehiclesInQueue[sizeofQueue];
front = 0;
rear = 0;
for(int i =0;i<sizeofQueue;i++){
vehiclesList[i] = new VehiclesInQueue();
}
}
/*Implementation of vehicleAdd method */
void vehicleAdd(int vehicleNumber,String typeOfVehicle){
if(rear == vehiclesList.length){
System.out.println("Lane is full! So wait with RED signal");
return;
}
vehiclesList[rear].vehicleNumber = vehicleNumber;
vehiclesList[rear].typeOfVehicle = typeOfVehicle;
rear++;
}
/*Implementation of vehicleRemove method */
void vehicleRemove(){
if(front == rear){
System.out.println("Lane is empty!");
return;
}
/*Removes front from the Lane */
System.out.println("Removed Vehicle is : "+vehiclesList[front++]);
}
public static void main(String[] args){
/*Declaration of Lane class object */
Lane laneObject;
laneObject = new Lane(5);
/*add the vehicles to lane */
laneObject.vehicleAdd(1, "2 Wheeler");
laneObject.vehicleAdd(2, "4 Wheeler");
laneObject.vehicleAdd(3, "4 Wheeler");
laneObject.vehicleAdd(4, "8 Wheeler");
laneObject.vehicleAdd(5, "2 Wheeler");
System.out.println("\n");
/*Display the vehicles from Lane */
for(int i =0;i<5;i++){
System.out.println("vehicles added at Lane = " +laneObject.toString());
}
System.out.println("\n");
/*remove vehicles from lane */
for(int j =0;j<5;j++){
laneObject.vehicleRemove();
}
_____________THE END_______________
}
}