-
Notifications
You must be signed in to change notification settings - Fork 0
Комит 1 итерации #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 |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| 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 int calculateDistance(int hours) { | ||
| return speed * hours; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,50 @@ | ||
| import java.util.ArrayList; | ||
| 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 leman = new Race(); | ||
| for (int i = 1; i <= 3; i++) {// цикл для записи имени и скорости 3-х автомобилей, и определения лидерства | ||
| String name;//имя автомобиля | ||
| while (true) { | ||
| System.out.println("Введите название автомобиля №" + i + ":"); | ||
| name = scanner.nextLine().trim();//исключаем название из одних пробелов | ||
| if (!name.isEmpty()) {//проверяем не пустой ли ввод | ||
| break; | ||
| } else { | ||
| System.out.println("Ошибка: название автомобиля не может быть пустым!"); | ||
| } | ||
| } | ||
|
Comment on lines
+10
to
+18
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. Код для считывания непустой строки с консоли лучше вынести в отдельную функцию, т.к. код, поделённый на небольшие функции, легко переиспользовать и поддерживать |
||
|
|
||
| int speed;//скорость автомобиля | ||
| while (true) {//бесконечный цикл для обработки ошибок ввода скорости | ||
| System.out.println("Введите скорость автомобиля №" + i + " (от 1 до 250 км/ч)"); | ||
| String input = scanner.nextLine().trim();//в input присваиваем введенную строку | ||
| if (input.matches("^[1-9]\\d{0,2}$")) {//устанавливаем правила ввода | ||
|
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. Лучше не регулярку проверять, а обернуть вызов |
||
| speed = Integer.parseInt(input);//преобразуем полученную строку в число | ||
| if (speed > 0 && speed <= 250) {//проверяем границы введенной скорости | ||
DenisRomanoff marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| break; | ||
| } else { | ||
| System.out.println("Ошибка: скорость должна быть от 1 до 250 км/ч");//сообщение об ошибке и повтор цикла | ||
| } | ||
| } else { | ||
| System.out.println("Ошибка: скорость должна быть целым числом");//сообщение об ошибке и повтор цикла | ||
| } | ||
| } | ||
| Car car = new Car(name, speed);//создаем автомобиль и присваиваем ему имя и скорость | ||
| leman.determinateLeader(car);//определяем занял ли автомобиль лидерство | ||
| } | ||
|
|
||
| System.out.println("Результаты гонки:");//выводим результат гонки | ||
| ArrayList<Car> leaders = leman.getLeaders(); | ||
|
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 (leaders.size() == 1) {//если в таблице лидеров 1 победитель | ||
| System.out.println("Самый быстрый автомобиль: " + leaders.getFirst().getName()); | ||
| } else {//если в таблице лидеров больше 1 победителя | ||
| System.out.println("Автомобили, разделившие первенство:"); | ||
| for (Car car : leaders) { | ||
| System.out.println(car.getName()); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| import java.util.ArrayList; | ||
|
|
||
| public class Race { | ||
| private String leaderName = ""; | ||
| private int leaderDistance = 0; | ||
| private ArrayList<Car> leaders = new ArrayList<>(); | ||
|
|
||
| public void determinateLeader(Car car) { | ||
| int distance = car.calculateDistance(24); | ||
|
|
||
| if (distance > leaderDistance) { | ||
| leaders.clear(); | ||
| leaders.add(car); | ||
| leaderDistance = distance; | ||
| } | ||
| else if (distance == leaderDistance) { | ||
| leaders.add(car); | ||
| } | ||
| } | ||
|
|
||
| public ArrayList<Car> getLeaders() { | ||
| return new ArrayList<>(leaders); | ||
| } | ||
| } |
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, тем самым исключив возможность их модификации извне, тогда можно геттеры будет удалить и обращаться напрямую к полям