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

Сдача проектной работы No1#1

Open
nsuhover wants to merge 4 commits intomyHomeworkProject1 from
master
Open

Сдача проектной работы No1 #1
nsuhover wants to merge 4 commits intomyHomeworkProject1 from
master

Conversation

@nsuhover
Copy link
Owner

@nsuhover nsuhover commented Dec 3, 2022

Сдаю проектную работу No1

s-buvaka and others added 3 commits July 27, 2022 23:03
Создан класс Calculator, который посчитывает общую введенную сумму товаров, делит её на равные части по количеству персон, а также определяет написание слов рубль и копейка в зависимости от введенной стоимости.
Создан класс ItemsBasket, который включает все в себя всю корзину введенных товаров за время рабоыт программы.
while (personsQuantity < 0) {personsQuantity = inputPersonsQuantity();} // получем колчиество персон
String itemName = inputItemName(1); // получаем имя первого товара
while (itemCost < 0) {itemCost = inputItemCost(itemName);} // получаем стоимость товара
new ItemsBasket();
Copy link

@gusar-off gusar-off Dec 4, 2022

Choose a reason for hiding this comment

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

Если ты используешь класс как утилиту со статическими методами, то ее не нужно инстанциировать. Относится к ItemsBasket и Calculator

public class ItemsBasket {
static String itemsNames = "None";

ItemsBasket() {
Copy link

@gusar-off gusar-off Dec 4, 2022

Choose a reason for hiding this comment

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

Лучше убрать

int errorInt = -1;
System.out.println("Введите число персон, на которых разделить счет:");
try {
int personsQuantity = scanner.nextInt(); // После запуска программа должна спрашивать у пользователя, на скольких человек необходимо разделить счёт.
Copy link

@gusar-off gusar-off Dec 4, 2022

Choose a reason for hiding this comment

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

У Scanner есть удобный метод hasNextInt, можно сразу узнать без дополнительных проверок возможно ли интерпретировать строку как int
Тогда достаточно будет сделать бесконечный цикл while(true) выход из которого осуществим только после получения правильного количества

double result = calculator.divideSum();
Formatter formatter = new Formatter();
public static String inputItemName(int type) {
Scanner scanner = new Scanner(System.in);
Copy link

@gusar-off gusar-off Dec 4, 2022

Choose a reason for hiding this comment

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

Лучшее переиспользовать инстанс сканнера, а не создавать каждый раз новый.

float errorFloat = -1.10f;

try {
itemCost = scanner.nextFloat();
Copy link

@gusar-off gusar-off Dec 4, 2022

Choose a reason for hiding this comment

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

У Scanner есть удобный метод hasNextFloat, можно сразу узнать без дополнительных проверок возможно ли интерпретировать строку как float
Точно также как и с int, достаточно будет бесконечного цикла с условием выхода - прочтение правильного числа


double divideSum() {
return totalPrice / friendsCount;
public static String findRightPennyWord (int penny){
Copy link

@gusar-off gusar-off Dec 4, 2022

Choose a reason for hiding this comment

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

На самом деле по заданию достаточно определять окончание только для рублей

System.out.println(item.name + " в корзине");
public static String findRightRoubleWord (int roubles){
String roubleName;
int lastDigit = -1;
Copy link

@gusar-off gusar-off Dec 4, 2022

Choose a reason for hiding this comment

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

Тут инициализация значением не обязательна

roubleName = "рубля";
return roubleName;
}
else if ((lastDigit >= 5 && lastDigit <= 9)||(lastDigit == 0)){
Copy link

@gusar-off gusar-off Dec 4, 2022

Choose a reason for hiding this comment

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

Можно else тут сделать, остальные варианты предусмотрели ранее

String roubleName;
int lastDigit = -1;
int lastTwoDigits = -11;
lastTwoDigits = roubles - (roubles / 100) * 100;
Copy link

@gusar-off gusar-off Dec 4, 2022

Choose a reason for hiding this comment

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

Можно брать остаток от деления на 100 в данном случае, нагляднее имхо

roubleName = "рублей";
return roubleName;
}
lastDigit = roubles - (roubles / 10) * 10;
Copy link

@gusar-off gusar-off Dec 4, 2022

Choose a reason for hiding this comment

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

А тут на 10

Copy link

Есть еще замечания по код стилям, в Android студии можно сделать авто форматирование нажав ПКМ по нужному классу и выбрав Reformat code, или нажать сочетание клавиш из соответствующего пункта в меню.
image
Пройдись по всем классам с автоформатированием

Copy link
Owner Author

nsuhover commented Dec 6, 2022 via email

Привет! Спасибо за фидбек. Пройдусь С уважением, Николай Суховерхов вс, 4 дек. 2022 г. в 21:55, gusar-off ***@***.***>:
...
Есть еще замечания по код стилям, в Android студии можно сделать авто форматирование нажав ПКМ по нужному классу и выбрав Reformat code, или нажать сочетание клавиш из соответствующего пункта в меню. [image: image] <https://user-images.githubusercontent.com/118199521/205509787-8633baa3-4caf-4397-8a5a-92ba52b89a76.png> Пройдись по всем классам с автоформатированием — Reply to this email directly, view it on GitHub <#1 (comment)>, or unsubscribe <https://github.com/notifications/unsubscribe-auth/A4LSIMJLPRL57G4OEEJWEVTWLTSLNANCNFSM6AAAAAASS6CRSI> . You are receiving this because you authored the thread.Message ID: ***@***.***>

- убраны лишние инициализации значениями;
- в классе Calculator поиск последней цифры и двух цифр изменены на остаток деления от 100 и 10 соответственно;
- сокращена логика определения окончания слова "рубль", убрана логика по определению копеек, т.к. не требовалось по ТЗ;
- убран стандартный пустой конструктор ItemsBasket;
- убрана инициализация статических методов из классов ItemsBasket и Calculator;
- для обработки ошибок ввода пользователя заменена логика с try catch на hasNextInt и hasNextFloat;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

1 more reviewer

@gusar-off gusar-off gusar-off 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 によって変換されたページ (->オリジナル) /