Skip to content
Open

dz #85

Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 88 additions & 1 deletion src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,93 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
Scanner myObj = new Scanner(System.in);
System.out.println("Введите число гостей (от 2 человек):");
int guests = 0;
try {
guests = myObj.nextInt();
myObj.nextLine(); // Очистка буфера после чтения числа
} catch (NumberFormatException e) {
System.out.println("Некорректное число гостей");
return;
}
if (guests <= 1) {
System.out.println("Некорректное число гостей");
return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🍏 При ошибочном вводе пользователя сразу выбрасывает из программы. Было бы круто дать ему возможность еще раз ввести данные. Для этого тебе нужно обернуть запросы на ввод в цикл

}
System.out.println("Введенное количество гостей: " + guests);

List<Item> items = new ArrayList<>();
while (true) {
System.out.println("Введите название товара:");
String itemName = myObj.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.

🍏 Сейчас пользователь может ввести вместо названия товара одни пробелы. Было бы классно исключить такой ввод. Для этого можно использовать метод строки trim, а потом проверить с помощью isEmpty.

if (itemName.equalsIgnoreCase("завершить")) {
break;
}
System.out.println("Введите стоимость товара:");
double itemPrice = 0;
try {
itemPrice = Double.parseDouble(myObj.nextLine());
} catch (NumberFormatException e) {
System.out.println("Неверная цена товара");
return;
}
if (itemPrice <= 0) {
System.out.println("Неверная цена товара");
return;
}
Item item = new Item(itemName, itemPrice);
items.add(item);
System.out.println("Добавлен товар: " + itemName + ", Цена: " + itemPrice);
System.out.println("Хотите ли добавить еще товар? (Введите 'Завершить', чтобы закончить)");
}

System.out.println("Список товаров:");
for (Item item : items) {
System.out.println(item.getName() + ", Цена: " + item.getPrice());
}

double result = calculateTotalGoods(items) / guests;
System.out.printf("Сумма на человека: %.2f %s", result, rubleEnding(result));
}

public static String rubleEnding(double amount) {
int rubles = (int) amount;
if (rubles % 10 == 1 && rubles % 100 != 11) {
return "рубль";
} else if (rubles % 10 >= 2 && rubles % 10 <= 4 && (rubles % 100 < 10 || rubles % 100 >= 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.

🍏 Здесь у тебя несколько раз происходит операция вычисления остатка от деления на 10 и на 100. Можно рассчитать их заранее, а затем использовать в блоке if-else.
Возможно, после такого преобразования тебе удобно будет применить вместо if-else оператор switch.
https://javarush.com/groups/posts/operator-switch-v-java

return "рубля";
} else {
return "рублей";
}
}

public static double calculateTotalGoods(List<Item> items) {
double totalGoods = 0;
for (Item item : items) {
totalGoods += item.getPrice();
}
return totalGoods;
}
}

class Item {
private String name;
private double price;

public Item(String name, double price) {
this.name = name;
this.price = price;
}

public String getName() {
return name;
}

public double getPrice() {
return price;
}
}