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
9 changes: 9 additions & 0 deletions src/main/java/Car.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
public class Car {
String name;
int 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, тем самым исключив возможность их модификации извне


Car(String name, int speed) {
this.name = name;
this.speed = speed;
}
}
36 changes: 36 additions & 0 deletions src/main/java/CheckInput.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import java.util.Scanner;

public class CheckInput {
Scanner scanner = new Scanner(System.in);
String carName;
int carSpeed;
String cancelInput = "Неправильный ввод. Попробуйте еще раз";

String checkInputName() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Здесь check не самый подходящий глагол для нейминга функции, т.к. функция не только проверяет, но считывает и возвращает считанное значение, гарантируя его корректность. Лучше назвать функцию например readName

while (true) {
if (!(scanner.hasNextInt())) {
carName = scanner.next();
if (carName.trim().isEmpty()) {
System.out.println("Вы ничего не ввели.");
} else return carName;
} else {
System.out.println(cancelInput);
}
scanner.next();
}
}

int checkInputSpeed() {

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) {
if (scanner.hasNextInt()) {
carSpeed = scanner.nextInt();
if (carSpeed < 0 || carSpeed > 250) {
System.out.println("Введите число, которое больше 0, но меньше или равно 250.");
} else return carSpeed;
} else {
System.out.println(cancelInput);
}
scanner.next();
}
}
}
24 changes: 22 additions & 2 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,26 @@

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
Car[] cars;
int number;
String carName;
int carSpeed;
Race race;

System.out.println("Давайте отправимся на автогонку \"24 часа Ле-Мана\" - и понаблюдаем за исходом событий!");
cars = new Car[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.

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

for (int i = 0; i < 3; i++) {
number = i + 1;
System.out.println("Введите название " + number + "-й машины.");
CheckInput input = new CheckInput();
carName = input.checkInputName();
System.out.println("Введите скорость " + number + "-й машины.");
carSpeed = input.checkInputSpeed();
cars[i] = new Car(carName, carSpeed);
System.out.println("Вы создали автомобиль " + carName + ", который едет со скоростью " + carSpeed + " км/ч");
}
race = new Race();
race.calculate(cars);
System.out.println("Самая быстрая машина: " + race.nameOfWinner);
System.out.println("За 24 часа она проехала " + race.bestDistance);
}
}
18 changes: 18 additions & 0 deletions src/main/java/Race.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
public class Race {
int bestDistance;
String nameOfWinner;
int distance;
Comment on lines +2 to +4

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Здесь эти переменные лучше спрятать за модификатором видимости private, а для получения машины-победителя использовать возвращаемое значение функции calculate

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.

Большое спасибо за подробный фидбек!


void calculate(Car[] cars) {
for (int i = 0; i < cars.length; i++) {
distance = cars[i].speed * 24;
if (i == 0) {
bestDistance = distance;
nameOfWinner = cars[i].name;
} else if (distance > bestDistance) {
bestDistance = cars[i].speed * 24;
nameOfWinner = cars[i].name;
} else return;
}
}
}