Skip to content

Conversation

@PanBuz
Copy link
Owner

@PanBuz PanBuz commented Feb 8, 2023

Вроде все работает...

Copy link

@SeveNChaK SeveNChaK left a comment

Choose a reason for hiding this comment

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

В некоторых файлах код прыгает, отступы не одинаковые - рекомендую использовать встроенные форматтер. Если ты программируешь в IDE от JetBrains, то можешь пройтись по всем файлам и нажать комбинацию (Windows: Shift + Ctrl + Alt + L, MacOS: Shift + Option + Command + L), затем выбрать, какую часть кода хочешь изменить, и выполнить команду. Среда разработки автоматически сделает нужные отступы и переносы (как она это делает можно изменить в настройках, но дефолтные значения вполне нормальные).

double summ = 0;
double money = 0;
int ost;
double ostl;

Choose a reason for hiding this comment

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

⏫ Все поля можно сделать приватными

Copy link
Owner Author

Choose a reason for hiding this comment

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

Сделал

int person;


while (!sc.hasNextInt()) {

Choose a reason for hiding this comment

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

⚠️ Проверки хватает на один раз. Если один раз ввести некорректный int, то првоерка пройдет, но отфильтруется ниже, а если потом ввести буквы, то приложение упадает ниже на sc.nextInt()

Copy link
Owner Author

Choose a reason for hiding this comment

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

Изменил, теперь должно быть все норм)

}


while (true) {

Choose a reason for hiding this comment

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

⏫ Думаю весь этот цикл можно объединить в один предыдущий и тогда можно решить проблему с вводом букв

Copy link
Owner Author

Choose a reason for hiding this comment

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

Разобрался подробнее, теперь все понял как надо, исправил)

cost = sc.nextDouble();
if (cost <= 0 ) {
System.out.println("Не корректное цифра");}
// else if (!sc.hasNextDouble()) {System.out.println("Буквы нельзя в стоимсть вводить");}

Choose a reason for hiding this comment

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

⚠️ Как раз не хватает этой проверки)

Copy link
Owner Author

Choose a reason for hiding this comment

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

Теперь все есть, должно работать)

}

summ = summ + cost;
nameAll = nameAll + "\n" + name;

Choose a reason for hiding this comment

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

⏫ Так как String является неизменяемым объектом, то при каждом сложении строк создаются новые объекты, что расходует память. Для таких случаев лучше использовать StringBuilder

Copy link
Owner Author

Choose a reason for hiding this comment

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

Так и не смог запустить программу с использованием этого класса, скинул пока без него, но буду изучать эту тему.

nameAll = nameAll + "\n" + name;

String messageTemplate1 = "Вы успешно добавили товар на общую сумму %.2f руб., добавьте товар еще, или наберите слово Завершить";
System.out.println(String.format(messageTemplate1, summ));

Choose a reason for hiding this comment

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

⏫ Можно заменить на System.out.printf(messageTemplate1, summ);

Copy link
Owner Author

Choose a reason for hiding this comment

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

Заменил)


money = summ / person;

ostl = money % 10f;

Choose a reason for hiding this comment

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

⚠️ Этого не достаточно, иногда нужно првоерять 2 последние цифры. Например, для чисел оканчивающихся на 11-14

Copy link
Owner Author

Choose a reason for hiding this comment

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

Заменил значение на 20, и добавил в свич вариантов до 19ти

case 9: rubli ="Рублей"; break;
}
String messageTemplate = "Вы заказали %s, скидываемся по %.2f %s.";
System.out.println(String.format(messageTemplate, nameAll, money, rubli));

Choose a reason for hiding this comment

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

⏫ Тут тоже можно подсократить, как писал уже выше

Copy link
Owner Author

Choose a reason for hiding this comment

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

сократил, пришлось немного помудрить с переносом строки


switch (ost){
case 0: rubli ="Рублей"; break;
case 1: rubli ="Рубль"; break;

Choose a reason for hiding this comment

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

⚠️ Для 11 это сработает не верно. Так же как и для 12-14

Copy link
Owner Author

Choose a reason for hiding this comment

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

добавил до 19ти

double money = 0;
int ost;
double ostl;
private double summ = 0;

Choose a reason for hiding this comment

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

⏫ Поля выше тоже можно сделать приватными


ostl = money % 10f;
ost = (int)ostl;
padegD = moneyPerPerson % 20f;

Choose a reason for hiding this comment

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

⚠️ Чтобы проверить 2 последние цифры нужно делить на 100, а не на 20. Ошибка со склонением все еще остается. Например, при общей сумме = 302, получаем 151 рублей.

И чтобы не делать большой свитч и все работало корретно, стоит просто получить 2 последние цифры числа (остаток от деления на 100), затем проверить, что это >=11 и <=14 (тогда пишем рублей), и если не попадет в это условие, то проверить уже остаток от деления на 10.

Copy link
Owner Author

Choose a reason for hiding this comment

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

Исправил, проверил выводом всех значений.

public class Ostatok {
void ostat (int padeg, double moneyPerPerson, String nameOfDishesAll){
void ostat (double moneyPerPerson, String nameOfDishesAll){
String rubli = new String();

Choose a reason for hiding this comment

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

String rubli = "";


padegD = moneyPerPerson % 100f;
if (padegD > 14) {padegD = padegD % 10f;}
padeg = (int) padegD;

Choose a reason for hiding this comment

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

Можно убрать лишние шаги и преобразования, и переменную

int padeg = ((int) moneyPerPerson) % 100;
if (padeg > 14) {
    padeg = padeg % 10;
}

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.

3 participants