Skip to content

Complete all tasks. - #1

Open
JohnGudron wants to merge 2 commits into
mainfrom
dev
Open

JohnGudron wants to merge 2 commits into
mainfrom
dev

Conversation

@JohnGudron

@JohnGudron JohnGudron commented Sep 3, 2024 •

Copy link
Copy Markdown
Owner

Поменял код, подробно в комментарии к новому коммиту.
Новый пулл реквест делать не стал, на будущее спросил в чате, как лучше. Если надо будет - буду делать новые)

Comment thread src/main/java/Race.java Outdated
}

public String findWinner() {
cars.sort(Comparator.comparing(car -> car.speed * 24));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Очень интересное решение для первого спринта

Comment thread src/main/java/Race.java Outdated
public class Race {

Scanner scanner = new Scanner(System.in);
ArrayList<Car> cars = new ArrayList<>();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Обычно из классов не торчат переменные, только методы.

@JohnGudron JohnGudron Sep 5, 2024 •

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А как лучше сделать - инициализировать сканер в main методе и передать его в конструктор Race класса или просто полностью вынести работу со Scanner в main метод?
Или вопрос в private просто и добавлении сеттера для cars?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сканер лучше иметь один на приложение. Можно передавать его внутрь класса, в этом нет ничего плохого.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да, изначальный комментарий был про сеттеры/геттеры.

Comment thread src/main/java/Race.java Outdated
Comment on lines +10 to +18
public Car takeInput(String carNum) {
System.out.printf("Введите через пробел имя и скорость %s автомобиля. Обращаем внимание, что скорость не может быть меньше 1 и больше 250.%n", carNum);
String[] input = scanner.nextLine().split(" ");
if (!checkSpeed(input[1])) {
System.out.println("Введена неверная скорость, повторите ввод");
takeInput(carNum);
}
return new Car(input[0], Integer.parseInt(input[1]));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Внутри этой же функции можно добавлять новую машину в список.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Логично)
А рекурсию так использовать норм или не стоит, чтобы на Stack over flow не нарваться?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В целом рекурсии лучше избегать, но конкретно в этом случае нормально, т.к. очень маловероятно, что стек уйдет глубоко.

 - make fields private
 - add getter for fields
 - p.s. don't know about record classes, so left it as it is

Change Race class:
 - make fields private

Change Race.takeInput:
 - add check for appropriate input (not only speed)
 - fix previous recursive call, cause it leads to crashes - make while instead
 - new recursive call (added for new check) have "return", so stack collapsing as it should

Change Race.checkSpeed:
 - add first check via regex
Comment thread src/main/java/Race.java

public static boolean checkSpeed(String speed) {
return Integer.parseInt(speed) > 0 && Integer.parseInt(speed) <= 250;
if (!(speed.matches("\\d+"))) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я бы лучше использовал что-то вроде такого: https://stackoverflow.com/questions/8391979/does-java-have-a-int-tryparse-that-doesnt-throw-an-exception-for-bad-data

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да, хотелось что-то типа toIntOrNull(), но сходу не нашел, решил так. Еще лишние скобки зачем-то)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В котоине будет такое, в джаве нет, насколько я помню. В целом реджексы лучше аккуратно использовать, потому что довольно дорогая вещь.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не задумывался про затратность реджексов - буду знать, спасибо. В целом, да, логичнее было бы трай кеч (раз строгих ограничений на имя нету) и завернуть бы его в экстеншн, для красоты)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants