Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

ПР по домашнему заданию по результатам 2 спринта#122

Closed
AshZoom wants to merge 19 commits intoYandex-Practicum:master from
AshZoom:master
Closed

ПР по домашнему заданию по результатам 2 спринта #122
AshZoom wants to merge 19 commits intoYandex-Practicum:master from
AshZoom:master

Conversation

@AshZoom
Copy link

@AshZoom AshZoom commented Nov 8, 2022

Направляю на проверку домашнее задание по результатам 2 спринта

Double result=0.00;

//вводим количество участников и сохраняем в переменной sTart
People sTart=new People();
Copy link

@faritowich faritowich Nov 9, 2022

Choose a reason for hiding this comment

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

  1. Название переменной sTart не совсем понятно. Лучше делать наименования более содержательными. Тема названий, да и не только хорошо раскрывается во 2 главе книги Роберта Мартина "Чистый код". Также на хабре есть краткий конспект книги: https://habr.com/ru/post/485118/
  2. Также все поля и методы класса помечены static, это означает, что для работы с ними не нужно создавать экземпляр класса, а можно вызвать его напрямую из класса, например People.countPeople()

Copy link
Author

Choose a reason for hiding this comment

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

Исправлено
"Также на хабре есть краткий конспект книги: https://habr.com/ru/post/485118/" @azat Nabiullin: Спасибо за рекомендацию!

System.out.println(list);
System.out.println(String.format("Итого: "+"%.2f"+" руб.",Products.total));
System.out.println("Делим на: "+sTart.numberOfPeople+" участников");
result=Products.total/sTart.numberOfPeople;
Copy link

@faritowich faritowich Nov 9, 2022

Choose a reason for hiding this comment

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

Можно People.numberOfPeople вместо sTart.numberOfPeople

Copy link
Author

Choose a reason for hiding this comment

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

Исправлено

//вывод данных
System.out.print("Всего добавлено в список: "+(Products.count-1)+" поз."+"\n");
System.out.println(list);
System.out.println(String.format("Итого: "+"%.2f"+" руб.",Products.total));
Copy link

@faritowich faritowich Nov 9, 2022

Choose a reason for hiding this comment

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

Можно использовать метод printf:

System.out.printf("Итого: "+"%.2f"+ "руб.%n",Products.total);

Copy link
Author

Choose a reason for hiding this comment

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

Исправлено.
@azat Nabiullin:
Я правильно понимаю разницу между методом println и printf (см/ ниже)?
Используем метод System.out.printf,т.к. хотим просто вывести строку в консоль. Если бы мы хотели получить отформатированную строку для дальнейшего использования в коде, используем System.out.println.

}

if (numberOfPeople <= 1) {
System.out.println("Неправильный ввод. Попробуйте ввести число участников ещё раз.");
Copy link

@faritowich faritowich Nov 9, 2022

Choose a reason for hiding this comment

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

Можно весь этот блок с if (numberOfPeople <= 1) просто перенести в блок else предыдущего if

Copy link
Author

Choose a reason for hiding this comment

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

Исправлено.
Спасибо! Т.к. это моя первая программа сразу не увидел такую возможность



String Name;//объявляем статическую переменную списка позиций для передачи в класс Main
Double Price;
Copy link

@faritowich faritowich Nov 9, 2022

Choose a reason for hiding this comment

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

В Java принята конвенция, по которой все имена переменных называются camelCase'ом, то есть с маленькой буквы. Почитать про конвенции названий можно здесь:
https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html

Copy link
Author

Choose a reason for hiding this comment

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

Исправлено.
@azat Nabiullin: Спасибо за рекомендацию!


Scanner scanner = new Scanner(System.in);
System.out.println("Укажите наименование Товара:");
String name1 = scanner.next();
Copy link

@faritowich faritowich Nov 9, 2022

Choose a reason for hiding this comment

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

Лучше избегать названий типа name1, price2 и т.д. Здесь можно назвать просто name.

Copy link
Author

Choose a reason for hiding this comment

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

Исправлено

name1=String.format( "Поз."+count+": "+name1+" "+ "%.2f"+" руб.",j);
System.out.println("Товар добавлен в список "+ name1);
count++;//количество позиций в списке
total=total+j;//вычисляем общую стоимость всех введенных товаров
Copy link

@faritowich faritowich Nov 9, 2022

Choose a reason for hiding this comment

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

Можно использовать короткую конструкцию total += j вместо total=total+j

Copy link
Author

Choose a reason for hiding this comment

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

Спасибо! Исправлено.

}

//метод проверки выхода из процесса составления списка товаров
public static Boolean exitOfList() {
Copy link

@faritowich faritowich Nov 9, 2022

Choose a reason for hiding this comment

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

Метод возвращает boolean, но при этом возвращаемый тип нигде не используется, а просто присваивается значение переменной finishOfList и в цикле while проверяется.
Так что в этом методе можно ничего не возвращать и сделать void, а возвращаемое значение убрать

Copy link
Author

Choose a reason for hiding this comment

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

Исправлено.

AshZoom and others added 10 commits November 14, 2022 13:41
} else{
finishOfList=true;
}
return;
Copy link

@faritowich faritowich Nov 27, 2022

Choose a reason for hiding this comment

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

В методах, не возвращающих результат (void) return в конце метода не нужен. return нужен для возвращения результата, а смысл в void в том, что он результат не возвращает.

Copy link
Author

Choose a reason for hiding this comment

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

Исправлено. Спасибо!


} else{
finishOfList=true;
}
Copy link

@faritowich faritowich Nov 27, 2022

Choose a reason for hiding this comment

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

Можно влю эту if-else конструкцию упростить до такой:
finishOfList= !add.equalsIgnoreCase("завершить");

Copy link
Author

Choose a reason for hiding this comment

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

Исправлено. Не знал о такой конструкции :(
Спасибо! Буду использовать.

String priceOfgood = scanner.next();
j = Double.parseDouble(priceOfgood);
if(j<0){
o=10/0;
Copy link

@faritowich faritowich Nov 27, 2022

Choose a reason for hiding this comment

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

Можно обойтись и без o=10/0, а просто выводить сообщение об ошибочном вводе. break в if нет так что и так будет повторный запрос ввода.
Кстати, когда надо искусственно вызвать ошибку, можно использовать конструкцию throw new Exception("Текст ошибки");

Copy link
Author

Choose a reason for hiding this comment

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

Исправлено. Я торопился сдать работу, чтобы успеть приступить к проектной работе No2, т.к. запутался как правильно оформлять Pull Request. Опыта в программировании нет и поэтому я решил задачу"в лоб" через костыли (деление на ноль).
Спасибо! Информацию по вызову ошибку записал для дальнейшего использования/

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

Reviewers

1 more reviewer

@faritowich faritowich faritowich left review comments

Reviewers whose approvals may not affect merge requirements

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Comments

AltStyle によって変換されたページ (->オリジナル) /