Repository navigation
24 часа Ле-Мана #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 |
|---|---|---|
| @@ -1 +1,5 @@ | ||
| # Пустой репозиторий для работы с Java кодом в Android Studio | ||
| # 24 часа Ле-Мана | ||
|
|
||
| 1. На вход из консоли получаем название и скорость машин (валидируем ввод) | ||
| 2. При сохранении машины проверяется лидер и обновляется при необходимости | ||
| 3. После ввода трех машин выводится лидер гонки |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,29 @@ | ||
| import model.Car; | ||
| import repository.RaceRepository; | ||
| import model.RaceState; | ||
| import service.RaceService; | ||
| import service.RaceServiceImpl; | ||
| import ui.ConsoleInputHandler; | ||
| import java.util.Scanner; | ||
|
|
||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
| RaceState raceState = new RaceState(); | ||
| RaceRepository raceRepository = new RaceRepository(); | ||
| Scanner scanner = new Scanner(System.in); | ||
| ConsoleInputHandler input = new ConsoleInputHandler(scanner); | ||
| RaceService raceService = new RaceServiceImpl(raceRepository, raceState); | ||
|
|
||
| System.out.println("*** Добро пожаловать на 24-х часовую гонку! ***"); | ||
| System.out.println("Введите название и скорость трех машин."); | ||
|
|
||
| for (int i = 1; i <= 3; i++) { | ||
| Car car = new Car(input.readCarName(i), input.readCarSpeed(i)); | ||
| raceService.addCar(car); | ||
| } | ||
|
|
||
| scanner.close(); | ||
|
|
||
| System.out.println("Самая быстрая машина: " + raceService.getLeader()); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| package model; | ||
|
|
||
| public class Car { | ||
| private final String name; | ||
| private final int speed; | ||
|
|
||
| public Car(String name, int speed) { | ||
| this.name = name; | ||
| this.speed = speed; | ||
| } | ||
|
|
||
| public String getName() { | ||
| return name; | ||
| } | ||
|
|
||
| public int getSpeed() { | ||
| return speed; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| package model; | ||
|
|
||
| public class RaceState { | ||
| private String leaderName = ""; | ||
| private int leaderDistance = 0; | ||
| private final int raceDuration = 24; | ||
|
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. Можно вынести в константу, добавив static модификатор -
Owner
Author
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 String getLeaderName() { | ||
| return leaderName; | ||
| } | ||
|
|
||
| public void setLeaderName(String leaderName) { | ||
| this.leaderName = leaderName; | ||
| } | ||
|
|
||
| public int getLeaderDistance() { | ||
| return leaderDistance; | ||
| } | ||
|
|
||
| public void setLeaderDistance(int leaderDistance) { | ||
| this.leaderDistance = leaderDistance; | ||
| } | ||
|
|
||
| public int getRaceDuration() { | ||
| return raceDuration; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| package repository; | ||
|
|
||
| import model.Car; | ||
|
|
||
| import java.util.ArrayList; | ||
|
|
||
| public class RaceRepository { | ||
| private final ArrayList<Car> cars = new ArrayList<>(); | ||
|
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 addCar(Car car){ | ||
| cars.add(car); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| package service; | ||
|
|
||
| import model.Car; | ||
|
|
||
|
|
||
| public interface RaceService { | ||
|
|
||
| void addCar(Car car); | ||
|
|
||
| String getLeader(); | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| package service; | ||
|
|
||
| import model.Car; | ||
| import repository.RaceRepository; | ||
| import model.RaceState; | ||
|
|
||
| public class RaceServiceImpl implements RaceService{ | ||
| private final RaceRepository raceRepository; | ||
| private final RaceState raceState; | ||
|
|
||
| public RaceServiceImpl(RaceRepository raceRepository, RaceState raceState) { | ||
| this.raceRepository = raceRepository; | ||
| this.raceState = raceState; | ||
| } | ||
|
|
||
| @Override | ||
| public void addCar(Car car){ | ||
| raceRepository.addCar(car); | ||
| updateLeader(car); | ||
| } | ||
|
|
||
| @Override | ||
| public String getLeader() { | ||
| return raceState.getLeaderName(); | ||
| } | ||
|
|
||
| private void updateLeader(Car car) { | ||
| int distance = car.getSpeed() * raceState.getRaceDuration(); | ||
| if (distance > raceState.getLeaderDistance()) { | ||
| raceState.setLeaderName(car.getName()); | ||
| raceState.setLeaderDistance(distance); | ||
| } | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| package ui; | ||
|
|
||
| import java.util.Scanner; | ||
|
|
||
| public class ConsoleInputHandler { | ||
| private final Scanner scanner; | ||
|
|
||
| public ConsoleInputHandler(Scanner scanner) { | ||
| this.scanner = scanner; | ||
| } | ||
|
|
||
| public String readCarName(int number) { | ||
| System.out.println("Введите название машины №" + number + ":"); | ||
|
|
||
| while (true) { | ||
|
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. Не рекомендую писать бесконечные циклы через |
||
| try { | ||
| String name = scanner.nextLine().trim(); | ||
| if (!name.isEmpty()) | ||
|
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. Код для считывания непустой строки с ввода лучше вынести в отдельную функцию - код, разделённый на небольшие функции, легче читать, поддерживать и переиспользовать |
||
| return name; | ||
| else | ||
| System.err.println("Название не может быть пустым"); | ||
| } catch (Exception e) { | ||
| System.err.println("Ошибка ввода"); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public int readCarSpeed(int number) { | ||
| System.out.println("Введите скорость машины №" + number + " в км/ч, не более 250:"); | ||
|
|
||
| while (true) { | ||
| try { | ||
| String input = scanner.nextLine().trim(); | ||
| if (input.isEmpty()) { | ||
| System.err.println("Скорость не может быть пустой"); | ||
| continue; | ||
| } | ||
| int speed = Integer.parseInt(input); | ||
| 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. Минимальную и максимальную скорости лучше вынести в константы для повышения читабельности кода
Owner
Author
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. просто не стал сильно заморачиваться ) |
||
| return speed; | ||
| } | ||
| System.err.println("Скорость должна быть от 1 до 250 км/ч"); | ||
| } catch (NumberFormatException e) { | ||
| System.err.println("Неправильная скорость. Введите целое число от 1 до 250"); | ||
| } | ||
| } | ||
| } | ||
| } | ||
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, то можно убрать геттеры и модификаторprivateи получать доступ к чтению полей напрямую