Repository navigation
Add car race winner logic #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: dev
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,17 @@ | ||
| public class Car { | ||
| private final String name; | ||
| private final int speed; | ||
|
|
||
| public Car(String name, int speed) { | ||
| this.name = name; | ||
| this.speed = speed; | ||
| } | ||
|
|
||
| public int calculateDistance(int hours) { | ||
| return hours * speed; | ||
| } | ||
|
|
||
| public String getName() { | ||
| return this.name; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,59 @@ | ||
| import java.util.Scanner; | ||
|
|
||
| public class Main { | ||
| private static Scanner scanner; | ||
|
|
||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
| scanner = new Scanner(System.in); | ||
| Car[] cars = makeRaceStartList(); | ||
|
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. От хранения массива машин и лишнего цикла при определении победителя можно избавиться, если при вводе данных сразу вычислять победителя и хранить его в отдельной переменной, тогда программа будет требовать меньше памяти и работать быстрее |
||
| Race race = new Race(cars); | ||
| Car winner = race.getLeader(); | ||
|
|
||
| if (winner != null) { | ||
| System.out.printf("Самая быстрая машина: %s%n", winner.getName()); | ||
| } else { | ||
| System.out.println("Победитель гонки не определен."); | ||
| } | ||
| } | ||
|
|
||
| public static Car[] makeRaceStartList() { | ||
| int CARS_TOTAL = 3; | ||
| Car[] raceMembers = new Car[CARS_TOTAL]; | ||
|
|
||
| for (int i = 1; i <= CARS_TOTAL; i++) { | ||
| String carName = getCarName(i); | ||
| int speed = getCarSpeed(i); | ||
|
|
||
| Car car = new Car(carName, speed); | ||
| raceMembers[i - 1] = car; | ||
| } | ||
| return raceMembers; | ||
| } | ||
|
|
||
| public static String getCarName(int index) { | ||
| String name = ""; | ||
|
|
||
| while (name.isEmpty()) { | ||
| System.out.printf("Введите название машины №%d:", index); | ||
| name = scanner.nextLine().trim(); | ||
| } | ||
|
|
||
| return name; | ||
| } | ||
|
|
||
| public static int getCarSpeed(int index) { | ||
| int speed = 0; | ||
|
|
||
| while (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. Минимальную и максимальную скорости лучше вынести в константы для повышения читабельности кода |
||
| System.out.printf("Введите скорость машины №%d (от 1 до 250 км/ч):", index); | ||
| try { | ||
| speed = scanner.nextInt(); | ||
| } catch (Exception e) { | ||
|
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. Не стоит отлавливать слишком абстрактные эксепшены, тут лучше именно InputMismatchException обработать |
||
| System.out.println("Допускаются только целые числа в диапазоне от 1 до 250. Попробуйте еще раз!"); | ||
| scanner.nextLine(); | ||
| } | ||
| } | ||
|
|
||
| return speed; | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| public class Race { | ||
| private final Car[] cars; | ||
| public Race(Car[] cars) { | ||
| this.cars = cars; | ||
| } | ||
| public Car getLeader() { | ||
| Car leader = null; | ||
| int maxDistance = 0; | ||
| for (Car car: cars) { | ||
| if (car == null) { | ||
| continue; | ||
| } | ||
|
|
||
| int distance = car.calculateDistance(24); | ||
| if (distance > maxDistance) { | ||
| maxDistance = distance; | ||
| leader = car; | ||
| } | ||
| } | ||
| return leader; | ||
| } | ||
| } |
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, то мы можем также надёжно и безопасно получать доступ к ним напрямую