Repository navigation
Expand file tree
/
Copy pathMain.java
More file actions
67 lines (58 loc) · 2.43 KB
/
Copy pathMain.java
File metadata and controls
67 lines (58 loc) · 2.43 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
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Set;
public class Main {
final static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
Car[] cars = new Car[3];
Set<String> usedNames = new HashSet<>(); //Здесь будет храниться список введенных названий машин
for (int i = 0; i < 3; i++) {
String carName;
int carSpeed;
while (true) {
System.out.printf("Введите название машины №%d: ", i + 1);
carName = inputCarName(i);
if (!usedNames.contains(carName)) {
usedNames.add(carName);
break;
} else {
System.out.printf("Машина %s уже существует. Пожалуйста, введите другое название.\n", carName);
}
}
carSpeed = inputCarSpeed(i);
cars[i] = new Car(carName, carSpeed);
}
Race race = new Race(cars);
Car leader = race.findLeader();
System.out.printf("Самая быстрая машина: %s", leader.getName());
}
public static String inputCarName(int i) {
while (true) {
String name = scanner.nextLine().trim();
if (!name.isEmpty()) {
return name;
} else {
System.out.println("Введено пустое название. Пожалуйста, введите название автомобиля.");
System.out.printf("Введите название машины №%d: ", i + 1);
}
}
}
public static int inputCarSpeed(int i) {
while (true) {
System.out.printf("Введите скорость машины №%d: ", i + 1);
try {
int speed = scanner.nextInt();
scanner.nextLine();
if (speed > 0 && speed <= 250) {
return speed;
} else {
System.out.println("Неправильная скорость");
}
} catch (InputMismatchException e) {
System.out.println("Ошибка: введено не число");
scanner.nextLine();
}
}
}
}