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
8 changes: 8 additions & 0 deletions src/main/java/Car.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
public class Car {
String carName;
int carSpeed;
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 Car(String carName, int carSpeed) {
this.carName = carName;
this.carSpeed = carSpeed;
}
}
48 changes: 46 additions & 2 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,50 @@

import java.util.ArrayList;
import java.util.Scanner;
public class Main {

public static void main(String[] args) {
System.out.println("Hello world!");
final int carsQuantity = 3;
int carSpeed;
String speedError = "- Неправильная скорость";

Scanner scanner = new Scanner(System.in);
Winner winner = new Winner();
ArrayList<Car> carStorage = new ArrayList<>();

Choose a reason for hiding this comment

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

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


for (int i = 1; i <= carsQuantity; i++) {

System.out.println("- Введите название машины №" + i + ":");
String carName = scanner.next();
scanner.nextLine();

while (true) {

Choose a reason for hiding this comment

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

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

System.out.println("- Введите скорость машины №" + i + ":");

if (!scanner.hasNextInt()) {
System.out.println(speedError);
scanner.next();
continue;
}

carSpeed = scanner.nextInt();

if (carSpeed <= 0 || carSpeed > 250) {
System.out.println(speedError);
continue;
}

break; //выход, в случае корректного ввода
}

carStorage.add(new Car(carName, carSpeed));

}
scanner.close();
winner.calculateWinner(carStorage);
System.out.println("Самая быстрая машина: " + winner.winnerStr);

}
}
}


23 changes: 23 additions & 0 deletions src/main/java/Winner.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import java.util.ArrayList;

public class Winner {
String winnerStr;

public void calculateWinner(ArrayList<Car> carStorage) {
double oldDistance = 0.0;
double newDistance;

for (int i = 1; i <= carStorage.size(); i++) {
Car carElement = carStorage.get(i-1); // получаем объект автомобиль
newDistance = carElement.carSpeed*24; // высчитываем расстояние, которое пройдет автомобиль

Choose a reason for hiding this comment

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

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


if (newDistance > oldDistance) { // если новое расстояние больше предыдущего
oldDistance = newDistance; // то переменная получает максимальное значение
winnerStr = carElement.carName; // победитель гонки обновляется

}
}


}
}