Repository navigation
Expand file tree
/
Copy pathRace.java
More file actions
77 lines (64 loc) · 2.62 KB
/
Copy pathRace.java
File metadata and controls
77 lines (64 loc) · 2.62 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
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Race {
private static final int CAR_COUNT = 3;
private static final int HOURS_COUNT = 24;
private final List<Car> carList;
public Race() {
carList = new ArrayList<>(CAR_COUNT);
}
//Сначала нужно задать участников гонки, а потом определять победителя, иначе метод вернет null
public String calculateWinnerAndGetName() {
Car leader = null;
for (int i = 0; i < CAR_COUNT; i++) {
carList.get(i).calculateAndSaveDistance(HOURS_COUNT);
if (leader != null) {
if (leader.getDistance() < carList.get(i).getDistance()) {
leader = carList.get(i);
}
} else {
leader = carList.get(i);
}
}
return leader.getName();
}
public void setParticipantsFromConsole(Scanner scanner) {
for (int i = 0; i < CAR_COUNT; i++) {
Car newParticipant = new Car();
//Сначала валидация и установка названия
while (true) {
System.out.println(String.format("— Введите название машины №%d:", i + 1));
String name = scanner.nextLine();
if (!name.isEmpty()) {
newParticipant.setName(name);
break;
} else {
System.out.println("Вы не ввели название");
}
}
//Затем валидация и установка скорости
while (true) {
System.out.println(String.format("— Введите скорость машины №%d:", i + 1));
String speedStr = scanner.nextLine();
if(speedStr.isEmpty()) {
System.out.println("Вы не ввели скорость");
continue;
}
int speed;
try {
speed = Integer.parseInt(speedStr);
} catch (NumberFormatException ex) {
speed = 0;
}
if(newParticipant.isSpeedValid(speed)) {
newParticipant.setSpeed(speed);
break;
} else {
System.out.println("Скорость должна быть указана от 0 до 250 км/ч");
}
}
carList.add(newParticipant);
}
}
}