Skip to content
Open
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
79 changes: 77 additions & 2 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,81 @@
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
Car[] cars = input2();
Race race = new Race(cars);
Car winner = race.winner();
System.out.println("Самая быстрая машина: " + winner.name);
}
}


private static Car[] input2() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Scanner scanner = new Scanner(System.in);
Car[] cars = new Car[3];
for (int i = 0; i < 3; i++) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

for (int i = 0; i < cars.length; i++) {

System.out.println("Введите название машины #" + (i + 1) + ": ");
String name = "";

while (scanner.hasNextInt()) {
System.out.println("Ошибка: введите не число");
scanner.next();
}

name = scanner.next();
int speed = 0;


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.

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

System.out.println("Введите скорость автомобиля #" + (i + 1) + " (км/ч): ");
scanner.nextLine();
if (!scanner.hasNextInt()) {
System.out.println("Ошибка: введите не строку");
continue;
}
speed = scanner.nextInt();
if (speed > 0 && speed <= 250) {
break;
} else {
System.out.println("Ошибка: скорость должна быть больше 0 и не более 250. Попробуйте снова.");
}
}

cars[i] = new Car(name, speed);
}
return cars;
}
}

class Car {
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.

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

int speed;


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

}
}

class Race {
Car[] cars;

Race(Car[] cars) {
this.cars = cars;
}

public Car winner() {
Car winner = null;
int maxDistance = 0;
for (Car current : cars) {
int distance = current.speed * 24;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Число 24 в формуле - магическая константа: из кода не видно, что это длительность гонки в часах. Такие значения лучше выносить в именованную константу, тогда формула читается сама по себе, а значение можно поменять в одном месте:

private static final int RACE_DURATION_HOURS = 24;
...
int currentDistance = RACE_DURATION_HOURS * car.getSpeed();

if (distance > maxDistance) {
maxDistance = distance;
winner = current;
}
}
return winner;
}

}