Skip to content

Проектная работа №1(Калькулятор на Java) - #1

Open
papcha07 wants to merge 2 commits into
mainfrom
dev
Open

papcha07 wants to merge 2 commits into
mainfrom
dev

Conversation

@papcha07

@papcha07 papcha07 commented Apr 5, 2024

Copy link
Copy Markdown
Owner

первая версия программы

Comment thread src/main/java/Calculator.java Outdated
public void addItem(Item item){
System.out.println("Товар " + item.name + " успешно добавлен");
itemList.add(item);
totalPrice += item.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.

Предлагаю вычислить общую сумму в цикле внутри метода printTotalInfo:

floar totalPrice = 0
for(Item item: itemList) {
   totalPrice  += item.price
}

Тогда можно будет удалить лишнюю переменную из класса

Comment thread src/main/java/Calculator.java Outdated
Comment on lines +29 to +30
System.out.printf("%d)%s\n",count,item.name);
count++;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно инкрементировать переменную прямо внутри вызова printf:

System.out.printf("%d)%s\n", count++, item.name);

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

System.out.printf("Общая сумма: %.2f %s\n",totalPrice,new Formatter().getEnding(totalPrice));
System.out.printf("Каждый должен заплатить: %.2f %s",(totalPrice/personCount),new Formatter().getEnding(totalPrice/personCount));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Для оптимизации кода и избежания лишних вычислений суммы, которую должен заплатить каждый человек, можно предварительно вычислить это значение и сохранить его в переменной:

float average = totalPrice / personCount;
System.out.printf("Каждый должен заплатить: %.2f %s", average, new Formatter().getEnding(average));

Comment thread src/main/java/Calculator.java Outdated
Comment on lines +10 to +12
ArrayList<Item> itemList = new ArrayList<>();
public int personCount;
public float totalPrice;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment thread src/main/java/Formatter.java Outdated
@@ -0,0 +1,22 @@
public class Formatter {

public float cost;

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

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.

Небольшая опечатка в слове Завершиить

Comment thread src/main/java/Main.java Outdated
Comment on lines +48 to +61
int count;
while(true){
System.out.println("Введите количество человек");
try {
count = Integer.parseInt(scanner.nextLine());
if(count < 1){
System.out.println("Некорректное количество человек");
}
else if(count == 1){
System.out.println("Не имеет смысла производить расчёты для одного человека");
}
else{
break;
}

@IvanGusevE IvanGusevE Apr 5, 2024 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Вместо использования оператора break можно попробовать сразу возвращать значение переменной count следующим образом:

try {
   int count = Integer.parseInt(scanner.nextLine());
   if (count < 1) {
   ...
    } else if (count == 1) {
    ....
    } else {
         return count;
    }
} catch (Exception e) {
...
}

Перемещение объявления переменной count ближе к месту ее использования улучшит читаемость кода.

Comment thread src/main/java/Main.java Outdated
break;
}
}
catch (Exception e){

@IvanGusevE IvanGusevE Apr 5, 2024 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Лучше перехватывать конкретное исключение NumberFormatException, возникающее при вызове метода Integer.parseInt, вместо перехвата всех исключений, наследующихся от Exception.

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

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

int wholePart = (int)cost;

if(wholePart % 10 == 1 && (wholePart % 11 != 11)){

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Условие wholePart % 11 != 11 всегда будет истинным, потому что результат операции % (остаток от деления) не может быть равен делителю.

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

public float cost;

public String getEnding(float cost){

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Метод можно сделать статическим, добавив ключевое слово static. Таким образом, другие части программы смогут вызывать этот метод, не создавая объект класса:

System.out.printf("Общая сумма: %.2f %s\n", totalPrice, Formatter.getEnding(totalPrice));

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