Repository navigation
Racing Simulator 1.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
skravchenko424
wants to merge
2
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
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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 +1 @@ | ||
| # Пустой репозиторий для работы с Java кодом в Android Studio | ||
| # Гоночный симулятор 1.0 |
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,30 @@ | ||
| public class Car { | ||
| private String name; // название автомобиля | ||
| private int speed; // скорость автомобиля, км/ч | ||
|
|
||
| public Car(String name, int speed) { | ||
| this.name = name; | ||
| this.speed = speed; | ||
| } | ||
|
|
||
| public String getName() { | ||
| return name; | ||
| } | ||
|
|
||
| public void setName(String name) { | ||
| this.name = name; | ||
| } | ||
|
|
||
| public int getSpeed() { | ||
| return speed; | ||
| } | ||
|
|
||
| public void setSpeed(int speed) { | ||
| this.speed = speed; | ||
| } | ||
|
|
||
| // Метод для вывода информации об автомобиле | ||
| public void displayInfo() { | ||
| System.out.println("Автомобиль: " + name + ", скорость: " + speed + " км/ч"); | ||
| } | ||
| } |
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,88 @@ | ||
|
|
||
| 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(); | ||
|
|
||
| System.out.println("Добро пожаловать в гоночный симулятор!"); | ||
| System.out.println("В гонке участвуют 3 автомобиля."); | ||
| System.out.println("Допустимая скорость автомобилей: от 1 до 250 км/ч\n"); | ||
|
|
||
| // Цикл для ввода данных о трёх автомобилях | ||
| for (int i = 1; i <= 3; i++) { | ||
| // Ввод названия автомобиля с проверкой | ||
| String name = inputCarNameValidation(scanner, i); | ||
|
|
||
| // Ввод скорости автомобиля с проверкой | ||
| int speed = inputSpeedValidation(scanner, i); | ||
|
|
||
| Car car = new Car(name, speed); | ||
|
|
||
| // Выводим информацию о введенном автомобиле | ||
| System.out.println("Автомобиль " + name + " (скорость: " + speed + " км/ч) добавлен."); | ||
|
|
||
| // Проверяем, стал ли новый автомобиль лидером | ||
| race.checkLeader(car); | ||
|
|
||
| System.out.println(); // Пустая строка для разделения | ||
| } | ||
|
|
||
| // Выводим итоги гонки | ||
| race.printRaceResults(); | ||
|
|
||
| scanner.close(); | ||
| } | ||
|
|
||
| private static String inputCarNameValidation(Scanner scanner, int carNumber) { | ||
| String name; | ||
|
|
||
| // Бесконечный цикл для проверки корректности ввода имени | ||
| while (true) { | ||
| System.out.println("Введите название автомобиля №" + carNumber + ":"); | ||
| name = scanner.nextLine(); | ||
|
|
||
| if (name.isBlank()) { | ||
| printErrorMessage("Ошибка: введено пустое название автомобиля."); | ||
| } else { | ||
| break; // Выходим из цикла если введено корректное имя | ||
| } | ||
| } | ||
|
|
||
| return name; | ||
| } | ||
|
|
||
| private static int inputSpeedValidation(Scanner scanner, int carNumber) { | ||
| int speed; | ||
|
|
||
| // Бесконечный цикл для проверки корректности ввода скорости | ||
| while (true) { | ||
| System.out.print("Введите скорость машины №" + carNumber + " (1-250 км/ч): \n"); | ||
|
|
||
| // Проверяем, ввел ли пользователь целое число | ||
| if (scanner.hasNextInt()) { | ||
| speed = scanner.nextInt(); | ||
|
|
||
| // Проверяем, находится ли скорость в допустимом диапазоне | ||
| if (speed > 0 && speed <= 250) { | ||
| scanner.nextLine(); // Очищаем буфер после nextInt() | ||
| break; // Выходим из цикла, если скорость корректна | ||
| } else { | ||
| printErrorMessage("Ошибка: скорость должна быть в диапазоне от 1 до 250 км/ч. Попробуйте снова."); | ||
| } | ||
| } else { | ||
| // Если пользователь ввел не число | ||
| String invalidInput = scanner.next(); | ||
| printErrorMessage("Ошибка: '" + invalidInput + "' не является допустимым целым числом. Попробуйте снова."); | ||
| } | ||
| // scanner.nextLine() не нужен здесь, так как мы уже считали некорректный ввод через next() или nextInt() | ||
| } | ||
|
|
||
| return speed; | ||
| } | ||
|
|
||
| private static void printErrorMessage( String message) { | ||
| System.out.println("\u001B[31m" + message + " \u001B[0m"); | ||
| } | ||
| } | ||
| } | ||
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,41 @@ | ||
| public class Race { | ||
| private String leaderName; | ||
| private int leaderDistance; | ||
|
|
||
| private static final int RACE_TIME = 24; | ||
|
|
||
| public Race() { | ||
| this.leaderName = ""; | ||
| this.leaderDistance = 0; | ||
| } | ||
|
|
||
| // Метод для определения нового лидера | ||
| public void checkLeader(Car car) { | ||
| int carDistance = RACE_TIME * car.getSpeed(); | ||
|
|
||
| // Сравниваем дистанцию нового автомобиля с дистанцией текущего лидера | ||
| if (carDistance > leaderDistance) { | ||
| leaderName = car.getName(); | ||
| leaderDistance = carDistance; | ||
| } | ||
| } | ||
|
|
||
| public String getLeaderName() { | ||
| return leaderName; | ||
| } | ||
|
|
||
| public int getLeaderDistance() { | ||
| return leaderDistance; | ||
| } | ||
|
|
||
| // Метод для вывода итогов гонки | ||
| public void printRaceResults() { | ||
| if (leaderName.isEmpty()) { | ||
| System.out.println("Гонка не состоялась или не было участников"); | ||
| } else { | ||
| System.out.println("\n=== ГОНКА ЗАВЕРШЕНА ==="); | ||
| System.out.println("Победитель: " + leaderName); | ||
| System.out.println("Пройденная дистанция: " + leaderDistance + " км"); | ||
| } | ||
| } | ||
| } |
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.
Закоментированный код лучше сразу удалять. Хранить закоментированный код в проекте - плохая практика, в случае чего этот код можно восстановить с помощью истории гита