-
Notifications
You must be signed in to change notification settings - Fork 0
Консольное приложение, спринт 2 #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,8 @@ | ||
| public class Car { | ||
| String carName; | ||
| int carSpeed; | ||
| public Car(String carName, int carSpeed) { | ||
| this.carName = carName; | ||
| this.carSpeed = carSpeed; | ||
| } | ||
| } | ||
| 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!"); | ||
| final int carsQuantity = 3; | ||
| int carSpeed; | ||
| String speedError = "- Неправильная скорость"; | ||
|
|
||
| Scanner scanner = new Scanner(System.in); | ||
| Winner winner = new Winner(); | ||
| ArrayList<Car> carStorage = 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. От хранения массива машин и лишнего цикла при определении победителя можно избавиться, если при вводе данных сразу вычислять победителя и хранить его в отдельной переменной, тогда программа будет требовать меньше памяти и работать быстрее |
||
|
|
||
| for (int i = 1; i <= carsQuantity; i++) { | ||
|
|
||
| System.out.println("- Введите название машины №" + i + ":"); | ||
| String carName = scanner.next(); | ||
| scanner.nextLine(); | ||
|
|
||
| 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. Код для считывания скорости с ввода лучше вынести в отдельную функцию - код, разделённый на небольшие функции, легче читать, поддерживать и переиспользовать |
||
| System.out.println("- Введите скорость машины №" + i + ":"); | ||
|
|
||
| if (!scanner.hasNextInt()) { | ||
| System.out.println(speedError); | ||
| scanner.next(); | ||
| continue; | ||
| } | ||
|
|
||
| carSpeed = scanner.nextInt(); | ||
|
|
||
| if (carSpeed <= 0 || carSpeed > 250) { | ||
| System.out.println(speedError); | ||
| continue; | ||
| } | ||
|
|
||
| break; //выход, в случае корректного ввода | ||
| } | ||
|
|
||
| carStorage.add(new Car(carName, carSpeed)); | ||
|
|
||
| } | ||
| scanner.close(); | ||
| winner.calculateWinner(carStorage); | ||
| System.out.println("Самая быстрая машина: " + winner.winnerStr); | ||
|
|
||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import java.util.ArrayList; | ||
|
|
||
| public class Winner { | ||
| String winnerStr; | ||
|
|
||
| public void calculateWinner(ArrayList<Car> carStorage) { | ||
| double oldDistance = 0.0; | ||
| double newDistance; | ||
|
|
||
| for (int i = 1; i <= carStorage.size(); i++) { | ||
| Car carElement = carStorage.get(i-1); // получаем объект автомобиль | ||
| newDistance = carElement.carSpeed*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. Число 24 лучше вынести в константу с говорящим названием для повышения читабельности кода |
||
|
|
||
| if (newDistance > oldDistance) { // если новое расстояние больше предыдущего | ||
| oldDistance = newDistance; // то переменная получает максимальное значение | ||
| winnerStr = carElement.carName; // победитель гонки обновляется | ||
|
|
||
| } | ||
| } | ||
|
|
||
|
|
||
| } | ||
| } | ||
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, тем самым исключив возможность их модификации извне