-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrain.java
More file actions
132 lines (94 loc) · 3.25 KB
/
Train.java
File metadata and controls
132 lines (94 loc) · 3.25 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package RailwayTrains;
public class Train {
private Locomotive locomotive;
public Train(Locomotive locomotive) {
this.locomotive = locomotive;
}
public boolean hasCars() {
return locomotive.getFirst() != null;
}
public void add(int index, Car car) {
if (index == 0) {
locomotive.setFirst(car);
} else {
Car current = locomotive.getFirst();
for (int i = 1; i < index; i++) {
current = current.getNext();
}
car.setNext(current.getNext());
current.setNext(car);
}
}
public int getPassengers() {
Car current = locomotive.getFirst();
int num = 0;
while (current != null) {
num = num + current.getCapacity();
current = current.getNext();
}
return num;
}
public double getLength() {
Car current = locomotive.getFirst();
double length = 0;
while (current != null) {
length = length + current.getLength();
current.getNext();
}
return length;
}
public Car removeFirst() {
Car removedCar = locomotive.getFirst();
locomotive.setFirst(removedCar.getNext());
return removedCar;
}
public void relink(Train train2) {
Car appendCar = train2.locomotive.getFirst();
Car currentTrainCar = locomotive.getFirst();
if (currentTrainCar == null) {
locomotive.setFirst(appendCar);
} else {
while (currentTrainCar.getNext() != null) {
currentTrainCar = currentTrainCar.getNext();
}
currentTrainCar.setNext(appendCar);
}
train2.locomotive.setFirst(null);
}
public void revert() {
Car pre = null;
Car cur = locomotive.getFirst();
Car next = cur.getNext();
while (cur != null) {
cur.setNext(pre);
pre = cur;
cur = next;
if (cur != null) {
next = cur.getNext();
}
}
locomotive.setFirst(pre);
}
public String toString() {
double locomotiveLength = locomotive.getLength();
int locomotiveType = locomotive.getType();
System.out.println("The data of this locomotive is: \n" + "Length: " + locomotiveLength + " meters; " + "Type: " + locomotiveType);
double carLength;
int carCapacity;
if (hasCars()) {
String info = "";
int numCars = 0;
Car current = locomotive.getFirst();
while (current != null) {
numCars++;
carLength = current.getLength();
carCapacity = current.getCapacity();
info = info + numCars + ". " + "Length: " + carLength + " meters; " + "Capacity: " + carCapacity + " ;\n";
current = current.getNext();
}
return "And this train has " + numCars + " cars. And the data of each car is listed here: \n" + info;
} else {
return "And this train has no cars";
}
}
}