-
Notifications
You must be signed in to change notification settings - Fork 0
1 попытка сдачи проекта #2
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
Changes from all commits
7a12b9d
b08e191
ab72d4c
25ab98f
c69c5ad
c64d5e2
6fb65e6
bff37af
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 |
|---|---|---|
| @@ -1 +1,10 @@ | ||
| # Пустой репозиторий для работы с Java кодом в Android Studio | ||
| # Проектная работа No1 «24 часа Ле-Мана» | ||
| Простое консольное приложение, которое будет вычислять, кто же станет победителем гонки. | ||
| Правила гонки такие: у всех машин есть 24 часа, и кто проедет за них большую дистанцию — тот и победил. | ||
|
|
||
| Критерии успешного выполнения: | ||
| 1. Приложение запрашивает у пользователя все данные: просит ввести названия автомобилей и их скорости. | ||
| 2. Приложение умеет корректно обрабатывать невалидный ввод данных. В случае невалидного ввода (нечисловое значение скорости, дробное значение скорости, скорость вне допустимого диапазона от 0 до 250, пустое название автомобиля и скорость) приложение выводит сообщение об ошибке и запрашивает повторный ввод данных до тех пор, пока не будут введены корректные значения. | ||
| 3. Весь код не написан в одном классе Main. | ||
| 4. Приложение успешно компилируется и выполняется без ошибок. | ||
| 5. Приложение корректно вычисляет и выводит победителя гонки |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| public class Car { | ||
| String name; | ||
| int speed; | ||
| int serialNumber; | ||
|
Comment on lines
+2
to
+4
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 name, int speed, int serialNumber) { | ||
| this.name = name; | ||
| this.speed = speed; | ||
| this.serialNumber = serialNumber; | ||
| } | ||
|
|
||
| public boolean isFaster(Car anotherCar) { | ||
| return this.speed > anotherCar.speed; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| import java.util.ArrayList; | ||
| import java.util.Scanner; | ||
|
|
||
| public class InteracterWithUserViaConsole { | ||
| public ArrayList<Car> getCarsForRace( int totalOfCars, int minSpeed, int maxSpeed) { | ||
| ArrayList<Car> carsForRace = new ArrayList<>(totalOfCars); | ||
|
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(String.format("В гонке участвуют %d машины.", totalOfCars)); | ||
| for (int currentSerialNumber=1; currentSerialNumber<=totalOfCars; currentSerialNumber++) { | ||
| carsForRace.add(getTrueCarInformation(currentSerialNumber, minSpeed, maxSpeed)); | ||
| } | ||
| return carsForRace; | ||
| } | ||
|
|
||
| private Car getTrueCarInformation(int serialNumber, int minSpeed, int maxSpeed) { | ||
| Scanner scanner = new Scanner(System.in); | ||
|
|
||
| System.out.println(String.format("Введите название машины No%d:", serialNumber)); | ||
| String nameOfCar = scanner.nextLine(); | ||
| while ( !isValidNameInformation(nameOfCar) ) { | ||
| System.out.println("Невалидный ввод."); | ||
| System.out.println(String.format("Введите название машины No%d:", serialNumber)); | ||
| nameOfCar = scanner.nextLine(); | ||
| } | ||
|
Comment on lines
+19
to
+23
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(String.format("Введите скорость машины (%d, %d]:", | ||
| minSpeed, maxSpeed)); | ||
| String speedOfCarInStringFormat = scanner.nextLine(); | ||
| while ( !isValidSpeedInformation(speedOfCarInStringFormat, minSpeed, maxSpeed) ) { | ||
| System.out.println("Невалидный ввод."); | ||
| System.out.println(String.format("Введите скорость машины (%d, %d]:", | ||
| minSpeed, maxSpeed)); | ||
| speedOfCarInStringFormat = scanner.nextLine(); | ||
| } | ||
|
|
||
| int speedOfCar = Integer.parseInt(speedOfCarInStringFormat); | ||
|
|
||
| Car anotherCar = new Car(nameOfCar, speedOfCar, serialNumber); | ||
| System.out.println(String.format("Машина No%d '%s' со скоростью %d добавлена.", | ||
| anotherCar.serialNumber, anotherCar.name, anotherCar.speed)); | ||
| return anotherCar; | ||
| } | ||
|
|
||
| private boolean isValidNameInformation(String name){ | ||
|
|
||
| return !name.isEmpty(); | ||
| } | ||
|
|
||
| private boolean isValidSpeedInformation(String speedInStringFormat, int minSpeed, int maxSpeed) { | ||
| Scanner scannerForInt = new Scanner(speedInStringFormat); | ||
| boolean speedIsValid = false; | ||
| if ( scannerForInt.hasNextInt() ) { | ||
| int speed = scannerForInt.nextInt(); | ||
| speedIsValid = speed>minSpeed && speed<=maxSpeed; | ||
| } | ||
| return speedIsValid; | ||
| } | ||
|
|
||
| public void printInformationAboutWinCar(Car winCar){ | ||
| System.out.println(String.format("К финишу первой пришла машина No%d '%s'.", | ||
| winCar.serialNumber, winCar.name)); | ||
| } | ||
|
|
||
|
|
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,20 @@ | ||
| import java.util.ArrayList; | ||
|
|
||
| public class Main { | ||
|
|
||
| public static int totalOFCars = 3; | ||
| public static int hoursInRace = 24; | ||
| public static int minSpeedOfVehicle = 0; | ||
| public static int maxSpeedOfVehicle = 250; | ||
|
Comment on lines
+5
to
+8
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. Молодец, что вынес эти значения в параметры, но лучше их сделать настоящими константами, для этого нужно добавить модификатор |
||
|
|
||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
| InteracterWithUserViaConsole interacter = new InteracterWithUserViaConsole(); | ||
| ArrayList<Car> cars = interacter.getCarsForRace(totalOFCars, minSpeedOfVehicle, maxSpeedOfVehicle); | ||
| Race race = new Race(cars, hoursInRace); | ||
| Car winCar = race.getWinnerCar(); | ||
| interacter.printInformationAboutWinCar(winCar); | ||
| } | ||
| } | ||
|
|
||
|
|
||
| } | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| import java.util.ArrayList; | ||
| public class Race { | ||
| ArrayList<Car> cars; | ||
| int hoursInRace; | ||
|
|
||
|
|
||
| Race(ArrayList<Car> cars, int hoursInRace) { | ||
| this.cars = cars; | ||
| this.hoursInRace = hoursInRace; | ||
| } | ||
|
|
||
|
|
||
| public Car getWinnerCar() { | ||
| Car winnerCar = cars.getFirst(); | ||
| for (int i=1; i<cars.size(); i++){ | ||
| if (!winnerCar.isFaster(cars.get(i))) winnerCar = cars.get(i); | ||
| } | ||
| return winnerCar; | ||
| } | ||
| } |