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
31 changes: 31 additions & 0 deletions src/main/java/Car.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
public class Car {
private static final int MAX_SPEED = 250;

private String name;
private int speed;
private int distance;

public String getName() {
return name;
}

public void setName(String name) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

this.name = name;
}

public void setSpeed(int speed) {
this.speed = speed;
}

public int getDistance() {
return distance;
}

public void calculateAndSaveDistance(int time) {
distance = speed * time;
}

public boolean isSpeedValid(int speed) {
return speed > 0 && speed <= MAX_SPEED;
}
}
12 changes: 11 additions & 1 deletion src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
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();
race.setParticipantsFromConsole(scanner);

String winnerName = race.calculateWinnerAndGetName();
System.out.println("Самая быстрая машина: " + winnerName);

scanner.close();
}
}
77 changes: 77 additions & 0 deletions src/main/java/Race.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Race {
private static final int CAR_COUNT = 3;
private static final int HOURS_COUNT = 24;

private final List<Car> carList;

public Race() {
carList = new ArrayList<>(CAR_COUNT);
}

//Сначала нужно задать участников гонки, а потом определять победителя, иначе метод вернет null
public String calculateWinnerAndGetName() {
Car leader = null;

for (int i = 0; i < CAR_COUNT; i++) {
carList.get(i).calculateAndSaveDistance(HOURS_COUNT);
if (leader != null) {
if (leader.getDistance() < carList.get(i).getDistance()) {
leader = carList.get(i);
}
} else {
leader = carList.get(i);
}
}
return leader.getName();
}

public void setParticipantsFromConsole(Scanner scanner) {
for (int i = 0; i < CAR_COUNT; i++) {
Car newParticipant = new Car();

//Сначала валидация и установка названия
while (true) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Не рекомендую писать бесконечные циклы через while (true) - лучше всегда явно прописывать условие выхода из цикла, чтобы уменьшить вероятность ошибиться и повысить читабельность кода

System.out.println(String.format("— Введите название машины №%d:", i + 1));

String name = scanner.nextLine();
if (!name.isEmpty()) {
newParticipant.setName(name);
break;
} else {
System.out.println("Вы не ввели название");
}
}

//Затем валидация и установка скорости

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Код для считывания скорости с ввода лучше вынести в отдельную функцию - код, разделённый на небольшие функции, легче читать, поддерживать и переиспользовать

while (true) {
System.out.println(String.format("— Введите скорость машины №%d:", i + 1));

String speedStr = scanner.nextLine();
if(speedStr.isEmpty()) {
System.out.println("Вы не ввели скорость");
continue;
}

int speed;
try {
speed = Integer.parseInt(speedStr);
} catch (NumberFormatException ex) {
speed = 0;
}

if(newParticipant.isSpeedValid(speed)) {
newParticipant.setSpeed(speed);
break;
} else {
System.out.println("Скорость должна быть указана от 0 до 250 км/ч");
}
}

carList.add(newParticipant);
}
}
}