Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

add logic of Main, Car and Race classes #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
MaxDDM wants to merge 1 commit into main
base: main
Choose a base branch
Loading
from dev
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
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
public class Car {
String name;
short speed;
Comment on lines +2 to +3
Copy link

@ArturNurtdinov ArturNurtdinov Feb 11, 2026

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, short speed) {
this.name = name;
this.speed = speed;
}
}
59 changes: 58 additions & 1 deletion src/main/java/Main.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,6 +1,63 @@
import static java.lang.Short.parseShort;

import java.util.Scanner;

public class Main {
public static short readSpeed(int carNumber) {
short speed = -1;
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Введите скорость машины No" + carNumber + ":");
String input = scanner.next();

try {
speed = parseShort(input);
} catch (NumberFormatException ignored) {
System.out.println("Введённое значение не удаётся преобразовать в целое число");
continue;
}

if (speed <= 0 || speed > 250) {
Copy link

@ArturNurtdinov ArturNurtdinov Feb 11, 2026

Choose a reason for hiding this comment

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

Минимальную и максимальную скорости лучше вынести в константы для повышения читабельности кода

System.out.println("Скорость должна быть положительным числом, не большим 250");
continue;
}

break;
} while (true);
Copy link

@ArturNurtdinov ArturNurtdinov Feb 11, 2026

Choose a reason for hiding this comment

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

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


return speed;
}

public static String readName(int carNumber) {
Scanner scanner = new Scanner(System.in);
String nameOfCar;

do {
System.out.println("Введите название машины No" + carNumber + ":");
nameOfCar = scanner.next();

if (nameOfCar.isEmpty()) {
System.out.println("Имя не может быть пустым");
}
} while(nameOfCar.isEmpty());

return nameOfCar;
}

public static Car createCar(int carNumber) {
String nameOfCar = readName(carNumber);
short speedOfCar = readSpeed(carNumber);

return new Car(nameOfCar, speedOfCar);
}

public static void main(String[] args) {
System.out.println("Hello world!");
Car car1 = createCar(1);
Car car2 = createCar(2);
Car car3 = createCar(3);
Comment on lines +55 to +57
Copy link

@ArturNurtdinov ArturNurtdinov Feb 11, 2026

Choose a reason for hiding this comment

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

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


Race race = new Race(car1, car2, car3);

System.out.println("Самая быстрая машина: " + race.whoIsLeader());
}
}
23 changes: 23 additions & 0 deletions src/main/java/Race.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
public class Race {
Car car1, car2, car3;
Copy link

@ArturNurtdinov ArturNurtdinov Feb 11, 2026

Choose a reason for hiding this comment

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

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


public Race(Car car1, Car car2, Car car3) {
this.car1 = car1;
this.car2 = car2;
this.car3 = car3;
}

public String whoIsLeader() {
// Достаточно просто сравнить скорости, без умножения на 24
Car car = car1;

if (car2.speed > car.speed) {
car = car2;
}
if (car3.speed > car.speed) {
car = car3;
}

return car.name;
}
}

AltStyle によって変換されたページ (->オリジナル) /