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
17 changes: 17 additions & 0 deletions src/main/java/Car.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
public class Car {
private final String name;
private final int speed;
Comment on lines +2 to +3

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Оба поля можно сделать публичными и убрать геттеры, т.к. они помечены final, то мы можем также надёжно и безопасно получать доступ к ним напрямую


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

public int calculateDistance(int hours) {
return hours * speed;
}

public String getName() {
return this.name;
}
}
57 changes: 55 additions & 2 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,59 @@
import java.util.Scanner;

public class Main {
private static Scanner scanner;

public static void main(String[] args) {
System.out.println("Hello world!");
scanner = new Scanner(System.in);
Car[] cars = makeRaceStartList();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

От хранения массива машин и лишнего цикла при определении победителя можно избавиться, если при вводе данных сразу вычислять победителя и хранить его в отдельной переменной, тогда программа будет требовать меньше памяти и работать быстрее

Race race = new Race(cars);
Car winner = race.getLeader();

if (winner != null) {
System.out.printf("Самая быстрая машина: %s%n", winner.getName());
} else {
System.out.println("Победитель гонки не определен.");
}
}

public static Car[] makeRaceStartList() {
int CARS_TOTAL = 3;
Car[] raceMembers = new Car[CARS_TOTAL];

for (int i = 1; i <= CARS_TOTAL; i++) {
String carName = getCarName(i);
int speed = getCarSpeed(i);

Car car = new Car(carName, speed);
raceMembers[i - 1] = car;
}
return raceMembers;
}

public static String getCarName(int index) {
String name = "";

while (name.isEmpty()) {
System.out.printf("Введите название машины №%d:", index);
name = scanner.nextLine().trim();
}

return name;
}

public static int getCarSpeed(int index) {
int speed = 0;

while (speed <= 0 || speed > 250) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Минимальную и максимальную скорости лучше вынести в константы для повышения читабельности кода

System.out.printf("Введите скорость машины №%d (от 1 до 250 км/ч):", index);
try {
speed = scanner.nextInt();
} catch (Exception e) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Не стоит отлавливать слишком абстрактные эксепшены, тут лучше именно InputMismatchException обработать

System.out.println("Допускаются только целые числа в диапазоне от 1 до 250. Попробуйте еще раз!");
scanner.nextLine();
}
}

return speed;
}
}
}
22 changes: 22 additions & 0 deletions src/main/java/Race.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
public class Race {
private final Car[] cars;
public Race(Car[] cars) {
this.cars = cars;
}
public Car getLeader() {
Car leader = null;
int maxDistance = 0;
for (Car car: cars) {
if (car == null) {
continue;
}

int distance = car.calculateDistance(24);
if (distance > maxDistance) {
maxDistance = distance;
leader = car;
}
}
return leader;
}
}