Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/main/java/Car.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
public class Car {

private final String name;
private final int speed;

public int getSpeed() {
return speed;
}

public String getName() {
return name;
}

public Car(String name, int speed) {
this.name = name;
this.speed = speed;
}

}
14 changes: 11 additions & 3 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@

public class Main {

public static void main(String[] args) {
System.out.println("Hello world!");

Race race = new Race();
System.out.println("Приветствуем Вас на гонке 24 часа Ле-Мана!");
race.takeInput("первого");
race.takeInput("второго");
race.takeInput("третьего");

System.out.println(race.findWinner());
}
}
}

41 changes: 41 additions & 0 deletions src/main/java/Race.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;

public class Race {

private final Scanner scanner = new Scanner(System.in);
private final ArrayList<Car> cars = new ArrayList<>();

public void takeInput(String carNum) {

System.out.printf("Введите через пробел имя и скорость %s автомобиля. Обращаем внимание, что скорость не может быть меньше 1 и больше 250.%n", carNum);
String[] input = scanner.nextLine().trim().split(" ");
if (input.length != 2) { // проверка правильности ввода через пробел
System.out.println("Не соблюден формат ввода, повторите ввод.");
takeInput(carNum);
return; // чтобы после отработки рекурсивного вызова метод не продолжал работу
}
while (!checkSpeed(input[1])) {
System.out.printf("Введите через пробел имя и скорость %s автомобиля. Обращаем внимание, что скорость не может быть меньше 1 и больше 250.%n", carNum);
input = scanner.nextLine().split(" ");
}
cars.add(new Car(input[0], Integer.parseInt(input[1]))); // фактический сеттер для cars
}

public static boolean checkSpeed(String speed) {
if (!(speed.matches("\\d+"))) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я бы лучше использовал что-то вроде такого: https://stackoverflow.com/questions/8391979/does-java-have-a-int-tryparse-that-doesnt-throw-an-exception-for-bad-data

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да, хотелось что-то типа toIntOrNull(), но сходу не нашел, решил так. Еще лишние скобки зачем-то)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В котоине будет такое, в джаве нет, насколько я помню. В целом реджексы лучше аккуратно использовать, потому что довольно дорогая вещь.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не задумывался про затратность реджексов - буду знать, спасибо. В целом, да, логичнее было бы трай кеч (раз строгих ограничений на имя нету) и завернуть бы его в экстеншн, для красоты)

System.out.println("Для ввода скорости можно использовать только цифры от 0 до 9");
return false;
} else if (!(Integer.parseInt(speed) > 0) || !(Integer.parseInt(speed) <= 250)) {
System.out.println("Введена недопустимая скорость, повторите ввод");
return false;
}
return true;
}

public String findWinner() {
cars.sort(Comparator.comparing(car -> car.getSpeed() * 24));
return String.format("Победителем стал автомобиль %s, проехав %d километров", cars.get(2).getName(), cars.get(2).getSpeed() * 24);
}
}