Skip to content

Проект 1 - #1

Open
Ilshatissimo wants to merge 5 commits into
mainfrom
dev
Open

Ilshatissimo wants to merge 5 commits into
mainfrom
dev

Conversation

@Ilshatissimo

Copy link
Copy Markdown
Owner

No description provided.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Race race = new Race();

        for (int i = 1; i <= 3; i++) {
            String name = "";
            while (true) {
                System.out.print("— Введите название машины №" + i + ": ");
                name = scanner.nextLine();
                if (!name.trim().isEmpty()) {
                    break;
                } else {
                    System.out.println("— Ошибка: Название автомобиля не может быть пустым");
                }
            }

            int speed = 0;
            while (true) {
                System.out.print("— Введите скорость машины №" + i + ": ");
                String speedInput = scanner.nextLine();

                if (speedInput.trim().isEmpty()) {
                    System.out.println("— Неправильная скорость");
                    continue;
                }

                try {
                    speed = Integer.parseInt(speedInput);

                    if (speed > 0 && speed <= 250) {
                        break;
                    } else {
                        System.out.println("— Неправильная скорость");
                    }
                } catch (NumberFormatException e) {
                    System.out.println("— Неправильная скорость");
                }
            }

            Car car = new Car(name, speed);
            race.checkNewParticipant(car);
        }

        race.printLeader();
    }
}

class Car {
    String name;
    int speed;

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

class Race {
    String leaderName = "";
    int maxDistance = 0;

    public void checkNewParticipant(Car car) {
        int distance = car.speed * 24;

        if (distance > maxDistance) {
            maxDistance = distance;
            leaderName = car.name;
        }
    }

    public void printLeader() {
        System.out.println("Самая быстрая машина: " + leaderName);
    }
}
Comment thread src/main/java/Main.java
while (true) {
System.out.print("— Введите название машины №" + i + ": ");
name = scanner.nextLine();
if (!name.trim().isEmpty()) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Отлично: Проверка пустого названия с trim закрывает и случай, когда введены только пробелы — здесь часто промахиваются.

Comment thread src/main/java/Main.java
}

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.

Можно лучше: Поля Car (здесь и в Race на строках 63–64) открыты для записи из любого места программы - Race читает car.speed мимо правил класса. Стоит пометить их private и давать доступ через простые методы чтения.

Comment thread src/main/java/Main.java
}

public void printLeader() {
System.out.println("Самая быстрая машина: " + leaderName);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно лучше: Вывод на экран живёт внутри Race, хотя по замыслу Race - «судья», который считает и хранит результат, а объявляет его Main. Если перенести печать в Main, а Race оставит метод, отдающий имя лидера, каждый класс останется про одно дело - такой код проще менять и переиспользовать.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants