Skip to content

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

Open
nsuhover wants to merge 4 commits into
myHomeworkProject1from
master
Open

nsuhover wants to merge 4 commits into
myHomeworkProject1from
master

Conversation

@nsuhover

@nsuhover nsuhover commented Dec 3, 2022

Copy link
Copy Markdown
Owner

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment thread src/main/java/ItemsBasket.java Outdated
public class ItemsBasket {
static String itemsNames = "None";

ItemsBasket() {

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

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 есть удобный метод hasNextInt, можно сразу узнать без дополнительных проверок возможно ли интерпретировать строку как int
Тогда достаточно будет сделать бесконечный цикл while(true) выход из которого осуществим только после получения правильного количества

Comment thread src/main/java/Main.java
double result = calculator.divideSum();
Formatter formatter = new Formatter();
public static String inputItemName(int type) {
Scanner scanner = new Scanner(System.in);

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
float errorFloat = -1.10f;

try {
itemCost = scanner.nextFloat();

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 есть удобный метод hasNextFloat, можно сразу узнать без дополнительных проверок возможно ли интерпретировать строку как float
Точно также как и с int, достаточно будет бесконечного цикла с условием выхода - прочтение правильного числа

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

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

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/Calculator.java Outdated
System.out.println(item.name + " в корзине");
public static String findRightRoubleWord (int roubles){
String roubleName;
int 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.

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

Comment thread src/main/java/Calculator.java Outdated
roubleName = "рубля";
return roubleName;
}
else if ((lastDigit >= 5 && lastDigit <= 9)||(lastDigit == 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.

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

Comment thread src/main/java/Calculator.java Outdated
String roubleName;
int lastDigit = -1;
int lastTwoDigits = -11;
lastTwoDigits = roubles - (roubles / 100) * 100;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment thread src/main/java/Calculator.java Outdated
roubleName = "рублей";
return roubleName;
}
lastDigit = roubles - (roubles / 10) * 10;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

А тут на 10

@gusar-off

Copy link
Copy Markdown

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

@nsuhover

nsuhover commented Dec 6, 2022 via email

Copy link
Copy Markdown
Owner Author

- убраны лишние инициализации значениями;
- в классе 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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants