forked from Yandex-Practicum/Java-Module-Project-YP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRace.java
More file actions
82 lines (70 loc) · 2.9 KB
/
Race.java
File metadata and controls
82 lines (70 loc) · 2.9 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
import java.util.InputMismatchException;
import java.util.Scanner;
public class Race {
private final static int MAX_SPEED = 250;
private final static int MIN_SPEED = 0;
private final static Scanner SCANNER = new Scanner(System.in);
private static Car winner = new Car("", -1);
public static void startRace() {
System.out.println("Добро пожаловать на гонки! Требуется ввести 3 автомобиля.");
for (int i = 1; i < 4; i++) {
System.out.println("=======================");
System.out.println("Введите название для " + i + " автомобиля");
String name = requestName();
int speed = requestSpeed();
Car car = new Car(name, speed);
winner = (winner.getKm() > car.getKm()) ? winner : car;
}
outputWinner(winner);
}
private static boolean checkCorrectName(String name) {
return name.isBlank();
}
private static boolean checkCorrectSpeed(int speed) {
return speed < MIN_SPEED || speed > MAX_SPEED;
}
private static String requestName() {
String name;
System.out.print("Название: ");
name = SCANNER.nextLine();
while (true) {
if (checkCorrectName(name)) {
System.out.println("Введена пустая строка. Повторите снова!");
System.out.print("Повторный ввод названия: ");
name = SCANNER.nextLine();
} else {
break;
}
}
return name;
}
private static int requestSpeed() {
int speed;
System.out.println("Введите скорость");
System.out.print("Cкорость (целое число от 0 до 250): ");
try {
speed = SCANNER.nextInt();
SCANNER.nextLine();
while (true) {
if (checkCorrectSpeed(speed)) {
System.out.println("Введена не верная скорость. Диапазон от 0 до 250");
System.out.print("Новое значение скорости: ");
speed = SCANNER.nextInt();
} else {
break;
}
}
} catch (InputMismatchException e) {
System.out.println("ОШИБКА: Скорость не может быть буквой или дробью");
System.out.println("-----------------");
SCANNER.nextLine();
speed = requestSpeed();
}
return speed;
}
private static void outputWinner(Car car) {
System.out.println("-------------------");
System.out.printf("Самый лучший и быстрый автомобиль: %s", car.getNAME());
SCANNER.close();
}
}