Repository navigation
Спринт 2. Проектная работа №1. #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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| public class Car { | ||
| public String nameCar; // Название автомобиля | ||
| public int speed; // Скорость автомобиля | ||
|
|
||
| // Конструктор | ||
| public Car(String name, int speed) { | ||
| this.nameCar = name; | ||
| this.speed = speed; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,39 @@ | ||
| import java.util.Scanner; | ||
|
|
||
|
|
||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
| Scanner scanner = new Scanner(System.in); | ||
| Race race = new Race(); // Экземпляр для отслеживания состояния гонки | ||
|
|
||
| // Вводим данные | ||
| for (int i = 1; i <= 3; i++) { | ||
| System.out.println("Введите название машины №" + i + ":"); | ||
| String name = scanner.next(); | ||
|
|
||
| int speed; | ||
| while (true) { | ||
| System.out.println("Введите скорость машины №" + i + ":"); | ||
| if (scanner.hasNextInt()) { // Проверяем, что введено число | ||
| speed = scanner.nextInt(); | ||
| if (speed >= 0 && speed <= 250) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Минимальную и максимальную скорости лучше вынести в константы с говорящим названием для повышения читабельности кода |
||
| break; // Выходим из цикла, если число в нужном диапазоне | ||
| } else { | ||
| System.out.println("Попробуйте ещё раз. Допустимая скорость: от 0 до 250."); | ||
| } | ||
| } else { | ||
| System.out.println("Попробуйте ещё раз. Нужно ввести целое число."); | ||
| scanner.next(); // Очищаем некорректный ввод | ||
| } | ||
| } | ||
|
|
||
| // Создаём автомобиль и проверяем его на лидерство | ||
| Car carUser = new Car(name, speed); | ||
| race.checkLeader(carUser); | ||
| } | ||
|
|
||
| // Выводим победителя | ||
| System.out.println("Самая быстрая машина: " + race.currentLeader); | ||
| scanner.close(); // Закрываем Scanner | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Молодец, что не забыл вызвать |
||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| public class Race { | ||
| public String currentLeader = ""; // Текущий лидер | ||
| public int distanceLeader = 0; // Дистанция текущего лидера | ||
|
Comment on lines
+2
to
+3
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Эти переменные лучше сделать приватными, чтобы у других классов не было возможности их изменения, а для получения названия машины-победителя лучше написать публичный геттер |
||
|
|
||
| // Метод для определения нового лидера | ||
| public void checkLeader(Car car) { | ||
| int distance = 24 * car.speed; // Пройденная дистанция за 24 часа | ||
|
|
||
| if (distance > distanceLeader) { | ||
| distanceLeader = distance; // Обновлённая дистанция лидера | ||
| currentLeader = car.nameCar; // Обновлённое название авто | ||
| } | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Поля лучше пометить
final, тем самым исключив возможность их модификации извне