Repository navigation
123 #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?
123 #1
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,6 @@ | ||
|
|
||
| //Компиляция | ||
| javac /home/alexandr/prj/android/Java-Module-Project-YP/src/main/java/Main.java | ||
|
|
||
| //Запуск | ||
| cd /home/alexandr/prj/android/Java-Module-Project-YP && java -cp src/main/java Main |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,122 @@ | ||
| import java.util.HashSet; | ||
| import java.util.Scanner; | ||
|
|
||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
| //Ввод данных | ||
| InputData input = new InputData(); | ||
| Car[] cars = input.getCars(); | ||
|
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. От хранения массива машин и лишнего цикла при определении победителя можно избавиться, если при вводе данных сразу вычислять победителя и хранить его в отдельной переменной, тогда программа будет требовать меньше памяти и работать быстрее |
||
|
|
||
| //расчёты | ||
| Calc calc = new Calc(); | ||
| Car fastest = calc.findFastest(cars); | ||
|
|
||
| //вывод результата | ||
| Output output = new Output(); | ||
| output.printResult(fastest); | ||
| } | ||
| } | ||
|
|
||
| class InputData { | ||
| private Scanner scanner = new Scanner(System.in); | ||
|
|
||
| public Car[] getCars() { | ||
| System.out.println("Эта программа - симулятор гонок. В гонках участвует 3 автомобиля."); | ||
| Car[] cars = new Car[3]; | ||
|
|
||
| for (int i = 0; i < 3; i++) { | ||
| System.out.println("\n--- Автомобиль " + (i + 1) + " ---"); | ||
|
|
||
| String name; | ||
| boolean validName; | ||
|
|
||
| do { | ||
| System.out.print("Введите имя машины " + (i + 1) + ": "); | ||
| name = scanner.nextLine(); | ||
|
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. Код для считывания непустой строки с ввода лучше вынести в отдельную функцию - код, разделённый на небольшие функции, легче читать, поддерживать и переиспользовать |
||
|
|
||
| // Проверяем, что имя не пустое | ||
| if (name.trim().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. Вместо |
||
| System.out.println("Ошибка! Имя не может быть пустым."); | ||
| validName = false; | ||
| continue; | ||
| } | ||
|
|
||
| // Проверяем, есть ли уже машина с таким именем | ||
| validName = true; | ||
| for (int j = 0; j < i; j++) { | ||
| if (cars[j] != null && cars[j].name.equalsIgnoreCase(name)) { | ||
| System.out.println("Ошибка! Машина с именем '" + name + "' уже существует."); | ||
| validName = false; | ||
| break; | ||
| } | ||
| } | ||
| } while (!validName); | ||
|
|
||
| int speed = inputSpeed(i + 1); | ||
| cars[i] = new Car(name, speed); | ||
| } | ||
|
|
||
| scanner.close(); | ||
| return cars; | ||
| } | ||
|
|
||
| //Метод для ввода скорости | ||
| private int inputSpeed(int carNumber) { | ||
| int speed = 0; | ||
| boolean validInput = false; | ||
|
|
||
| while (!validInput) { | ||
| try { | ||
| System.out.print("Введите скорость машины " + carNumber + " (1-250 км/ч): "); | ||
| String input = scanner.nextLine(); | ||
| 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. Минимальную и максимальную скорости лучше вынести в константы для повышения читабельности кода |
||
| validInput = true; | ||
| } else { | ||
| System.out.println("Ошибка! Скорость должна быть в диапазоне от 1 до 250 км/ч."); | ||
| } | ||
| } catch (NumberFormatException e) { | ||
| System.out.println("Ошибка! Введите целое число."); | ||
| } | ||
| } | ||
|
|
||
| return speed; | ||
| } | ||
| } | ||
|
|
||
| class Calc { | ||
| //Метод для расчёта самой быстрой машины | ||
| public Car findFastest(Car[] cars) { | ||
| Car fastest = null; | ||
| for (Car car : cars) { | ||
| if (fastest == null || car.speed > fastest.speed) { | ||
| fastest = car; | ||
| } | ||
| } | ||
| return fastest; | ||
| } | ||
| } | ||
|
|
||
| class Output { | ||
| //Вывод | ||
| public void printResult(Car fastest) { | ||
| System.out.println("Самая быстрая машина: " + fastest.name); | ||
| } | ||
| } | ||
|
|
||
| // Класс машина | ||
| class Car { | ||
| // Поля | ||
| String name; // Название | ||
| int speed; // Скорость (км/ч) | ||
| int distance; // Расстояние за 24 часа езды (км) | ||
|
Comment on lines
+112
to
+114
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. Поля лучше пометить |
||
|
|
||
| // Конструктор | ||
| Car(String carName, int carSpeed) { | ||
| name = carName; | ||
| speed = carSpeed; | ||
| distance = carSpeed * 24; | ||
| } | ||
| } | ||
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.
Сами скомпилированные файлы .class не нужно копировать в source директории и пушить на гит