forked from Yandex-Practicum/Java-Module-Project-YP
-
Notifications
You must be signed in to change notification settings - Fork 0
черновой вариант для проверки #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
nehwe
wants to merge
3
commits into
main
Choose a base branch
from
dev
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,32 @@ | ||
| import java.util.ArrayList; | ||
|
|
||
| import lemana.model.Auto; | ||
| import lemana.model.LemanaUserInput; | ||
| import lemana.model.Race; | ||
|
|
||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
|
|
||
| LemanaUserInput userInput = new LemanaUserInput(); | ||
| userInput.startUserInput(); | ||
|
|
||
| ArrayList<Auto> raceAutos = userInput.getRaceAutos(); | ||
|
|
||
| // После успешного ввода рассчитываем, | ||
| // сколько километров за 24 часа | ||
| // смог проехать каждый участник гонки (автомобиль), | ||
| // и запоминаем лидера. | ||
| Race race = new Race(raceAutos); | ||
| for (Auto auto : raceAutos) { | ||
| race.getDistanceForRaceAuto(auto); | ||
| } | ||
|
|
||
| String leaderName = userInput.getLeader().name; | ||
|
|
||
| // Выводим название автомобиля-лидера в консоль | ||
| // в любом понятном формате. | ||
| // Например: Самая быстрая машина: Москвич. | ||
| System.out.printf("Участник на автомобиле'%s' выигрывает гонку", | ||
| leaderName); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| package lemana.model; | ||
|
|
||
| // Автомобиль — объект, содержащий в себе параметры «название» и «скорость». | ||
| public class Auto { | ||
| public String name; | ||
| public int velocity; | ||
|
|
||
| public Auto(String name, int velocity) { | ||
| this.name = name; | ||
| this.velocity = velocity; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| // Алиса AI подсказала вариант с использованием регулярных выражений | ||
| // для проверки валидности ввода пользователя | ||
| package lemana.model; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.Scanner; | ||
|
|
||
| public class LemanaUserInput { | ||
| // Запрашиваем у пользователя 3 автомобиля, | ||
| // каждый из которых имеет два параметра: | ||
| // название и скорость. | ||
| Scanner scanner = new Scanner(System.in); | ||
| private ArrayList<Auto> raceAutos; | ||
| int maxVelocity = 0; | ||
| Auto leader; | ||
|
|
||
| public void startUserInput() { | ||
| System.out.println("Добро пожаловать на автогонки!"); | ||
| System.out.println("Для их проведения требуются трое участников."); | ||
| System.out.println("Oбъявите участников: ... "); | ||
|
|
||
| String name; | ||
| int velocity; | ||
| int index = 1; | ||
|
|
||
| raceAutos = new ArrayList<>(); | ||
|
|
||
| // Приложение умеет корректно обрабатывать невалидный ввод данных. | ||
| // В случае невалидного ввода (нечисловое значение скорости, дробное значение скорости, | ||
| // скорость вне допустимого диапазона от 0 до 250, пустое название автомобиля и скорость) | ||
| // приложение выводит сообщение об ошибке и запрашивает повторный ввод данных до тех пор, | ||
| // пока не будут введены корректные значения. | ||
| while (raceAutos.size() < 3) { | ||
|
|
||
| name = getValidInput("Введите название авто учаcтника №%d: ", index); | ||
| velocity = getValidInput("Укажите скорость '%s' (от 0 до 250): ", name); | ||
|
|
||
| Auto raceAuto = new Auto(name, velocity); | ||
|
|
||
| if (raceAutos.add(raceAuto)) { | ||
| System.out.printf("Aвтомобиль '%s' успешно внесен " + | ||
| "в список участников\n", raceAuto.name); | ||
| index++; | ||
| if(isLeader(raceAuto)) { | ||
| leader = raceAuto; | ||
| } | ||
| } else { | ||
| System.out.println("Что-то пошло не так, участник не в списке"); | ||
| } | ||
|
|
||
| } | ||
| scanner.close(); | ||
| } | ||
|
|
||
| public ArrayList<Auto> getRaceAutos() { | ||
| return raceAutos; | ||
| } | ||
|
|
||
| // Проверяем ввод на валидность | ||
| public boolean isValid(String userInput){ | ||
| if (!userInput.matches("-?\\d+(\\.\\d+)?")) { | ||
| System.out.println("Невалидный ввод: нечисловое значение скорости."); | ||
| return false; | ||
| } else if (!userInput.matches("-?\\d+")) { | ||
| System.out.println("Невалидный ввод: дробное значение скорости."); | ||
| return false; | ||
| } else { | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| public boolean isValid(int userInput){ | ||
| if (userInput > 0 && userInput < 251) { | ||
| return true; | ||
| } else { | ||
| System.out.println("Невалидный ввод: скорость превышает допустимый диапазон."); | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| public boolean isEmptyValue(String userInput) { | ||
| if (userInput.trim().isEmpty()) { | ||
| System.out.println("Невалидный ввод: пустое значение."); | ||
| return true; | ||
| } else { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| public String getValidInput(String message, int index) { | ||
| String input = ""; | ||
| boolean isValid = false; | ||
| while (!isValid) { | ||
| System.out.printf(message, index); | ||
| input = scanner.next(); | ||
| isValid = !isEmptyValue(input); | ||
| } | ||
| return input; | ||
| } | ||
|
|
||
| public int getValidInput(String message, String str) { | ||
| String input; | ||
| int processedInput = -1; | ||
| boolean isValid = false; | ||
| while (!isValid) { | ||
| System.out.printf(message, str); | ||
| input = scanner.next(); | ||
| if (!isEmptyValue(input) && isValid(input)) { | ||
| processedInput = Integer.parseInt(input); | ||
| } | ||
| isValid = isValid(processedInput); | ||
| } | ||
| return processedInput; | ||
| } | ||
|
|
||
| public boolean isLeader(Auto raceAuto) { | ||
| if(raceAuto.velocity > getMaxVelocity()) { | ||
| setMaxVelocity(raceAuto.velocity); | ||
| return true; | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| public int getMaxVelocity(){ | ||
| return this.maxVelocity; | ||
| } | ||
|
|
||
| public void setMaxVelocity(int value){ | ||
| maxVelocity = value; | ||
| } | ||
|
|
||
| public Auto getLeader() { | ||
| return this.leader; | ||
| } | ||
|
|
||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| package lemana.model; | ||
|
|
||
| import java.util.ArrayList; | ||
|
|
||
| // Гонка – класс, в котором рассчитывается и запоминается лидер. | ||
| public class Race { | ||
|
|
||
| final ArrayList<Auto> raceAutos; | ||
| // длительность гонки 24 часа | ||
| final int raceTime = 24; | ||
|
|
||
| public Race(ArrayList<Auto> raceAutos) { | ||
| this.raceAutos = raceAutos; | ||
| } | ||
|
|
||
| // путь пройденный участником(авто) за 24 часа; | ||
| public void getDistanceForRaceAuto(Auto raceAuto) { | ||
| int distance = raceAuto.velocity * raceTime; | ||
| System.out.printf("\nАвто '%s' за %d часа проехал %d км.", | ||
| raceAuto.name, raceTime, distance); | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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, тем самым исключив возможность их модификации извне