Add: a5 close #9
This commit is contained in:
58
assignment5/Question5/ManyVehicles.java
Normal file
58
assignment5/Question5/ManyVehicles.java
Normal file
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* 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<Vehicle> vehicles;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public ManyVehicles() {
|
||||
// initialise instance variables
|
||||
vehicles = new ArrayList<Vehicle>();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 averageSpeed() {
|
||||
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.averageSpeed() == 80.0);
|
||||
} catch (Exception e) {
|
||||
System.out.println("Error uncaught exception: " + e.getClass().getName() + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user