import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Shopping {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
ArrayList<Double> prices = new ArrayList<>();
try (Scanner fileScanner = new Scanner(new File("products.txt"))) {
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine().trim();
if (line.isEmpty()) continue;
int lastSpace = line.lastIndexOf(' ');
if (lastSpace == -1) continue;
String name = line.substring(0, lastSpace);
double price = Double.parseDouble(line.substring(lastSpace + 1));
names.add(name);
prices.add(price);
}
} catch (FileNotFoundException e) {
System.out.println("Файл products.txt не найден");
return;
} catch (NumberFormatException e) {
System.out.println("Ошибка в цене в файле");
return;
}
if (names.isEmpty()) {
System.out.println("Файл пустой");
return;
}
Scanner scanner = new Scanner(System.in);
double total = 0;
int count = 0;
String cart = "";
System.out.println("===== АССОРТИМЕНТ =====");
for (int i = 0; i < names.size(); i++) {
System.out.println((i + 1) + ". " + names.get(i) + " — " + prices.get(i) + " руб.");
}
System.out.println("=======================");
System.out.println("Пиши название. Чтобы закончить — 0");
while (true) {
System.out.print("Какой товар вам нужен? ");
String input = scanner.nextLine().trim();
if (input.equals("0")) break;
int index = -1;
for (int i = 0; i < names.size(); i++) {
if (names.get(i).equalsIgnoreCase(input)) {
index = i;
break;
}
}
if (index == -1) {
System.out.println("Нет в ассортименте");
continue;
}
String name = names.get(index);
double price = prices.get(index);
cart += name + " — " + price + " руб.\n";
total += price;
count++;
System.out.println("Товар в корзине: " + name);
System.out.println("Продолжить или 0 для остановки");
}
if (count == 0) {
System.out.println("Корзина пустая");
return;
}
double average = total / count;
double vat = total * 0.20;
double withVat = total + vat;
System.out.println("\n===== ВАША КОРЗИНА =====");
System.out.print(cart);
System.out.println("-------------------------");
System.out.println("Товаров: " + count);
System.out.printf("Итого: %.2f руб.%n", total);
System.out.printf("Средняя цена: %.2f руб.%n", average);
System.out.printf("НДС 20%%: %.2f руб.%n", vat);
System.out.printf("К оплате с НДС: %.2f руб.%n", withVat);
}
}