-
Notifications
You must be signed in to change notification settings - Fork 90
/
Car.java
56 lines (47 loc) · 1.42 KB
/
Car.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.util.ArrayList;
public class Car {
private ArrayList<Passenger> passengers;
private int maxCapacity;
public Car(int maxCapacity) {
this.maxCapacity = maxCapacity;
this.passengers = new ArrayList<>();
}
public int getCapacity() {
return maxCapacity;
}
public int seatsRemaining() {
return maxCapacity - passengers.size();
}
public void addPassenger(Passenger passenger) {
if (seatsRemaining() == 0) {
throw new RuntimeException("Car is full");
}
passengers.add(passenger);
}
public void removePassenger(Passenger passenger) {
if (!passengers.contains(passenger)) {
throw new RuntimeException("Passenger not on this car");
}
passengers.remove(passenger);
}
public void printManifest() {
if (passengers.isEmpty()) {
System.out.println("This car is EMPTY.");
} else {
System.out.println("Passengers on this car:");
for (Passenger passenger : passengers) {
System.out.println("- " + passenger);
}
}
}
public static void main(String[] args) {
Car myCar = new Car(100);
try {
while (true) {
myCar.printManifest();
}
} catch (Exception e) {
System.err.println(e.getMessage()); // Out of fuel
}
}
}