/* * Author: CHEN Yongyuan (Walter) 1930006025 from OOP(1007) * Date: 2022-04-24 * Description: ManyVehicles class manipulate many vehicles */ import java.util.ArrayList; public class ManyVehicles { private ArrayList vehicles; /** * Constructor. */ public ManyVehicles() { // initialise instance variables vehicles = new ArrayList(); } /** * Add any kind of vehicle to the arraylist. * * @param v the vehicle to be added */ public void addVehicle(Vehicle v) { vehicles.add(v); } /** * Calculate the avergae speed of all vehicles. * * @return the average speed of all vehicles */ public double calcAvgSpeed() { double totalSpeed = 0; for (Vehicle v : vehicles) { totalSpeed += v.getSpeed(); } return totalSpeed / vehicles.size(); } /** * Test. */ public static void testManyVehicles() { try { ManyVehicles mv = new ManyVehicles(); mv.addVehicle(new Car(100, 100)); mv.addVehicle(new Car(90)); mv.addVehicle(new Aircraft(100, 70, 3900)); mv.addVehicle(new Train(100, 60)); System.out.println(mv.calcAvgSpeed() == 80.0); } catch (Exception e) { System.out.println("Error uncaught exception: " + e.getClass().getName() + e.getMessage()); } } }