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
22 changes: 22 additions & 0 deletions src/main/java/Car.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
public class Car {
private String name;
private double 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, double speed) {
this.name = name;
this.speed = speed;
}

public String getName() {
return name;
}

public double getSpeed() {
return speed;
}


public double calculateDistance() {
return speed * 24;
}
}
65 changes: 63 additions & 2 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,67 @@

import java.util.Scanner;

public class Main {
private static final Scanner scanner = new Scanner(System.in);
private static final int CAR_COUNT = 3;
private static final double MIN_SPEED = 0;
private static final double MAX_SPEED = 250;

public static void main(String[] args) {
System.out.println("Hello world!");
System.out.println("Добро пожаловать на гонку! Введите данные о 3 автомобилях.");

Race race = new Race();


for (int i = 1; i <= CAR_COUNT; i++) {
System.out.println("\nВведите данные для автомобиля №" + i + ":");
Car car = createCar();
race.addCar(car);
}


race.determineLeader();


Car leader = race.getLeader();
if (leader != null) {
System.out.println("\nСамая быстрая машина: " + leader.getName());
} else {
System.out.println("\nНе удалось определить лидера гонки.");
}

scanner.close();
}


private static Car createCar() {
String name = getCarName();
double speed = getValidSpeed();
return new Car(name, speed);
}


private static String getCarName() {
System.out.print("Название автомобиля: ");
return scanner.nextLine();
}


private static double getValidSpeed() {
double speed;
while (true) {
Comment thread
Karen927 marked this conversation as resolved.
System.out.print("Скорость автомобиля (км/ч): ");
try {
speed = Double.parseDouble(scanner.nextLine());
if (speed > MIN_SPEED && speed <= MAX_SPEED) {
break;
} else {
System.out.println("Ошибка: скорость должна быть больше 0 и не превышать 250 км/ч. Попробуйте ещё раз.");
}
} catch (NumberFormatException e) {
System.out.println("Ошибка: введите корректное числовое значение скорости.");
}
}
return speed;
}
}
}
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.List;

public class Race {
private List<Car> cars;

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.

Артур, благодарю. Исправлю

private Car leader;

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


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


public void determineLeader() {
if (cars.isEmpty()) {
leader = null;
return;
}

leader = cars.get(0);
double maxDistance = leader.calculateDistance();

for (Car car : cars) {
double currentDistance = car.calculateDistance();
if (currentDistance > maxDistance) {
maxDistance = currentDistance;
leader = car;
}
}
}


public Car getLeader() {
return leader;
}
}