-
Notifications
You must be signed in to change notification settings - Fork 0
Homework #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?
Homework #1 #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,20 @@ | ||
| public class Auto { | ||
|
|
||
|
|
||
| private String carName; | ||
| private int carSpeed; | ||
|
|
||
|
|
||
| public Auto(String carName, int carSpeed) { | ||
| this.carName = carName; | ||
| this.carSpeed = carSpeed; | ||
| } | ||
|
|
||
| public String getName() { | ||
| return carName; | ||
| } | ||
|
|
||
| public int getCarSpeed() { | ||
| return carSpeed; | ||
| } | ||
|
Comment on lines
+13
to
+19
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. Можно убрать две функции - геттеры, сделать переменные публичными и добавить к ним модификатор final - так часто делают с классами, у которых переменные инициализируются в конструкторе и никогда не меняются (дата классы) |
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,66 @@ | ||
| import java.util.ArrayList; | ||
| import java.util.Scanner; | ||
|
|
||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
| System.out.println(""" | ||
| Добро пожаловать на Гонку «24 часа Ле-Мана»! | ||
| Пожалуйста, введите название и скорость для каждого автомобиля, участвующего в Гонке. | ||
| Программа вычислит и выведет победителя гонки."""); | ||
|
|
||
| ArrayList<Auto> cars = new ArrayList<>(); | ||
|
|
||
| for (int i = 1; i <= 3; i++) { | ||
| System.out.println("Введите название автомобиля № " + i); | ||
| String carName = getName(); | ||
| System.out.println("Введите скорость автомобиля № " + i); | ||
| int carSpeed = getSpeed(); | ||
|
|
||
| cars.add(new Auto(carName, carSpeed)); | ||
| } | ||
|
|
||
| Auto winner = Race.determineWinner(cars); | ||
| System.out.printf("Победителем Гонки «24 часа Ле-Мана» становится автомобиль марки \"%s\".", winner.getName()); | ||
|
|
||
| } | ||
|
|
||
| public static String getName() { | ||
| Scanner scanName = new Scanner(System.in); | ||
| boolean validInput = false; | ||
| String name = ""; | ||
| while (!validInput) { | ||
| name = scanName.nextLine(); | ||
| if (name.isEmpty()) { | ||
| System.out.println("Ошибка: название автомобиля не может быть пустым, пожалуйста, введите корректное название."); | ||
| } else { | ||
| validInput = true; | ||
| } | ||
| } | ||
| return name; | ||
| } | ||
|
|
||
|
|
||
| public static int getSpeed() { | ||
| Scanner scanCar = new Scanner(System.in); | ||
| int speed = 0; | ||
| boolean validInput = false; | ||
|
|
||
|
|
||
| while (!validInput) { | ||
| try { | ||
| speed = Integer.parseInt(scanCar.nextLine()); | ||
| if (speed <= 250 && speed >= 0) { | ||
| validInput = true; | ||
| } else if (speed < 0) { | ||
| System.out.println("Ошибка: cкорость автомобиля не может принимать отрицательное значение, введите корректное число."); | ||
| } else { | ||
| System.out.println("Ошибка: скорость автомобиля по условиям Гонки «24 часа Ле-Мана» не может превышать 250 км/ч, введите корректное число."); | ||
| } | ||
|
|
||
| } catch (NumberFormatException e) { | ||
| System.out.println("Ошибка: введено некорректное значение. Пожалуйста, введите целое число от 0 до 250."); | ||
| } | ||
| } | ||
| return speed; | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| import java.util.ArrayList; | ||
|
|
||
| public class Race { | ||
| public static Auto determineWinner(ArrayList<Auto> cars) { | ||
| Auto winner = cars.get(0); | ||
| int theBiggestDistance = 0; | ||
| for (Auto car : cars) { | ||
| int distance = car.getCarSpeed() * 24; | ||
| if (distance > theBiggestDistance) { | ||
| theBiggestDistance = distance; | ||
| winner = car; | ||
| } | ||
| } | ||
| return winner; | ||
|
Comment on lines
+5
to
+14
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. Здесь можно избавиться от этого цикла и хранения машин в массиве, если определять текущую машину-победителя при чтении данных, тем самым программа будет требовать меньше памяти и работать быстрее |
||
| } | ||
| } | ||
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, тем самым исключив возможность их модификации