Skip to content

Домашнее задание (Проектная работа №1) - #1

Open
GabovAleksander wants to merge 2 commits into
mainfrom
dev
Open

GabovAleksander wants to merge 2 commits into
mainfrom
dev

Conversation

@GabovAleksander

Copy link
Copy Markdown
Owner

Проектная работа №1

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


private static String getCurrencyText(BigDecimal price){

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🍏 Лучше вынести этот метод в отдельный класс Formatter, чтобы его можно было использовать в разных частях приложения.

Comment thread src/main/java/Main.java Outdated
String roundPrice=price.toBigInteger().toString();
String currency;
int lastDigit=Integer.parseInt(roundPrice.substring(roundPrice.length()-1));
if (lastDigit==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.

⚠️ Этот алгоритм не предусматривает случаев от 11 по 14. В этих случаях тоже должно быть "рублей"

Comment thread src/main/java/Main.java
Check check;
Integer countPerson;

NumberFormat nf = NumberFormat.getCurrencyInstance();

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/Main.java Outdated
person= EnterData.enterGuest(check.getCountPerson());

//Приводим к валюте и убираем обозначение валюты
Position position=new Position(nameDish,price,person);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🍏 Немного поехало форматирование. Для форматирования кода и удаления неиспользуемых импортов применяй следующие сочетания клавиш:
Windows: Control+Alt+L
MacOS: Command+Option+L
Больше горячих клавиш можно найти здесь: https://developer.android.com/studio/intro/keyboard-shortcuts

Comment thread src/main/java/Main.java
Comment on lines +63 to +64
System.out.println(
String.format("Добавленные товары: %s. %-50s %20s %s Гость №%s",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🍏 Можно упростить вот так:

Suggested change
System.out.println(
String.format("Добавленные товары: %s. %-50s %20s %s Гость №%s",
System.out.printf("Добавленные товары: %s. %-50s %20s %s Гость №%s%n",

Comment thread src/main/java/Main.java Outdated
Comment on lines +74 to +86
for(int i=1;i<=check.getCountPerson();i++){
int count=0;
BigDecimal itog=BigDecimal.ZERO;
for (Position position:check.getPositionList()
) {
if (position.getGuest().equals(i)){
count++;
itog=itog.add(position.getPrice());
System.out.println(
String.format("%s. %-50.45s %20s %s",
count, position.getName(), nf.format(position.getPrice()), getCurrencyText(position.getPrice())));
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🍏 Здесь получился сложный алгоритм с вложенным циклом. Если у тебя будет 20 гостей и 40 блюд (каждый гость заказал по 2 блюда), то ты пройдешь по массиву блюд 20 раз. Можно создать map или массив чисел по количеству гостей, пройти по массиву блюд один раз и записать для каждого гостя итоговую сумму.

BigDecimal price;
String readLine;
while (true) {
System.out.println("Введите цену блюда: ");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🍏 Круто было бы подсказать пользователю, в каком формате от него ожидаются данные. Например, [руб,коп]

try {
Scanner scanner = new Scanner(System.in);
readLine = scanner.nextLine();
if(readLine.trim().length()-readLine.trim().indexOf(".")<=3||readLine.trim().indexOf(".")==-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.

🍏

Suggested change
if(readLine.trim().length()-readLine.trim().indexOf(".")<=3||readLine.trim().indexOf(".")==-1) {
if(readLine.trim().length()-readLine.trim().indexOf(".")<=3|| !readLine.trim().contains(".")) {

System.out.println("Введите цену блюда: ");
try {
Scanner scanner = new Scanner(System.in);
readLine = scanner.nextLine();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🍏 Для получения сразу числа с дробной частью можно использовать методы scanner.nextFloat, scanner.nextBigDecimal. Перед ними лучше сделать проверку scanner.hasNextFloat/scanner.hasNextBigDecimal или обработать исключение.

Comment thread src/main/java/EnterData.java Outdated

public class EnterData {
public static Integer enterGuest(Integer countInCheck){
Integer person;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🍏 В большинстве случаев для простых операций достаточно использовать примитивный тип - int. О разнице можно почитать, например, вот здесь: https://habr.com/ru/articles/104231/

@kgornostaeva

Copy link
Copy Markdown

Привет, Александр! Извини за задержку с проверкой твоей работы!

@GabovAleksander

Copy link
Copy Markdown
Owner Author

Привет, Александр! Извини за задержку с проверкой твоей работы!

Привет, Екатерина! Ничего страшного в задержке нет :). В целом с замечаниями, кроме одного согласен, но т.к. задание учебное не хотелось на него тратить лишнее время. Не согласен с нулевой стоимостью блюда, в задании нет ничего про нулевую стоимость, есть только про отрицательную. В целом нулевая вполне может быть, подарок клиенту на день рождения, просто какая-то акция или замена блюда. Это было предусмотрено изначально и соответствует ТЗ вроде как.

@GabovAleksander GabovAleksander left a comment

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.

Согласен с 11-19 при получении падежа, не согласен с 0 ценой блюда.

if(readLine.trim().length()-readLine.trim().indexOf(".")<=3||readLine.trim().indexOf(".")==-1) {
price = new BigDecimal(readLine);
if(price.compareTo(BigDecimal.ZERO)>=0){
//Предыдущее условие >= соответствовало критериям задачи, стоимость не могла быть отрицательной, в данном случае она не может быть и нулевой,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

👌 👌 👌
Комментарий лучше оставить средствами git, а не в коде, чтобы они не оставались в проекте)

String currency;
if (roundPrice.length()>1){
int lastDigits = Integer.parseInt(roundPrice.substring(roundPrice.length() - 2));
if(lastDigits>10&&lastDigits<20){

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🍏 Для повышения читабельности:

Suggested change
if(lastDigits>10&&lastDigits<20){
if (lastDigits > 10 && lastDigits < 20) {

Comment thread src/main/java/Main.java
BigDecimal devidedSum=check.getTotalSum().divide(new BigDecimal(check.getCountPerson()),2,RoundingMode.HALF_UP);
System.out.println("При делении на всех, каждый должен заплатить: "+nf.format(devidedSum)+getCurrencyText(devidedSum));
BigDecimal devidedSum = check.getTotalSum().divide(new BigDecimal(check.getCountPerson()), 2, RoundingMode.HALF_UP);
System.out.println("При делении на всех, каждый должен заплатить: " + nf.format(devidedSum) + Formatter.getCurrencyText(devidedSum));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🍏 При печати в памяти будут создаваться промежуточные строки из-за использования оператора "+".  Можно использовать StringBuilder, который сформирует только результирующую строку, или printf https://habr.com/ru/articles/260767/

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