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/Auto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
public class Auto {
String name;
int speed;
Comment on lines +2 to +3

Choose a reason for hiding this comment

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

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


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

public String getName() {
return name;
}

public int getSpeed() {
return speed;
}
}


42 changes: 40 additions & 2 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,44 @@
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
Scanner scanner = new Scanner(System.in);
Race race = new Race();

for (int i = 1; i <= 3; i++) {
System.out.println("Автомобиль #" + i);

String name = getName(scanner);
int speed = getValidSpeed(scanner, name);

race.addCar(new Auto(name, speed));
System.out.println("Текущий лидер: " + race.getCurrentLeader());
}

System.out.println("\nФинальный победитель: " + race.getCurrentLeader());
}

private static String getName(Scanner scanner) {
System.out.print("Название: ");
return scanner.nextLine();
}

private static int getValidSpeed(Scanner scanner, String name) {
while (true) {
System.out.print("Скорость для " + name + " (1-250): ");

if (scanner.hasNextInt()) {
int speed = scanner.nextInt();
scanner.nextLine(); // Очистка буфера

if (speed > 0 && speed <= 250) {

Choose a reason for hiding this comment

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

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

return speed;
}
System.out.println("Ошибка: скорость должна быть 1-250!");
} else {
System.out.println("Ошибка: введите целое число!");
scanner.nextLine(); // Очистка неверного ввода
}
}
}
}
}
26 changes: 26 additions & 0 deletions src/main/java/Race.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import java.util.ArrayList;

public class Race {
String currentLeaderName = "Лидер отсутствует";
int currentLeaderDistance = 0;
Comment on lines +4 to +5

Choose a reason for hiding this comment

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

Данные поля можно сделать приватными (пометив их модификатором private), так как в данном классе для получения имени победителя уже есть геттер, а сами поля лучше всегда скрывать, чтобы не было возможности снаружи этого класса сломать ему логику работы

ArrayList<Auto> cars = new ArrayList<>();

Choose a reason for hiding this comment

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

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


public void addCar(Auto car) {
cars.add(car);
updateLeader(car);
}

private void updateLeader(Auto newCar) {
int newDistance = 24 * newCar.getSpeed();

if (newDistance > currentLeaderDistance) {
currentLeaderDistance = newDistance;
currentLeaderName = newCar.getName();
}
}

public String getCurrentLeader() {
return currentLeaderName;
}
}