实例化集合用反射方式完成

(2)实例化集合类(用反射的方式完成实例化〉(1)定义商品类
(2)实例化集合类(用反射的方式完成实例化〉v
(3)功能1:遍历集合显示出商品信息(商品编号从小到大)。
(4)功能2:查找各种类别,最高和最低商品。(stream Collections)。
(5)功能3:增加一个商品到集合(编号不能重复,要做处理)
(6)功能4:删除指定编号的商品,不存在有提示
(7)功能5:退出或因异常程序要退出的时候,开启线程将集合序列化到product..ser.文件中。下次运行时候读取 product.er.反序列化得到集合,并能在此基础上继续进行增加或删除数据。
(8)功能6:有功能菜单,可以反复选择上述功能。v
(9)功能7:筛选食品类别中价格最高的前3个商品,并遍历显示商品信息。(用stream)。
(10)功能8: Scanner输入的异常要求处理,不要中止程序。

引用 皆我百晓生 小程序回复内容作答:

下面是一个示例代码,实现了上述功能:

import java.io.*;
import java.util.*;
import java.lang.reflect.*;

class Product implements Serializable {
    private int id;
    private String name;
    private String category;
    private double price;

    public Product(int id, String name, String category, double price) {
        this.id = id;
        this.name = name;
        this.category = category;
        this.price = price;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getCategory() {
        return category;
    }

    public double getPrice() {
        return price;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", category='" + category + '\'' +
                ", price=" + price +
                '}';
    }
}

public class Main {
    private static List<Product> products = new ArrayList<>();
    private static String fileName = "product.ser";

    public static void main(String[] args) {
        loadProducts();
        displayMenu();
    }

    private static void loadProducts() {
        try {
            File file = new File(fileName);
            if (file.exists()) {
                FileInputStream fis = new FileInputStream(file);
                ObjectInputStream ois = new ObjectInputStream(fis);
                products = (List<Product>) ois.readObject();
                ois.close();
                fis.close();
                System.out.println("Products loaded from " + fileName);
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static void saveProducts() {
        try {
            FileOutputStream fos = new FileOutputStream(fileName);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(products);
            oos.close();
            fos.close();
            System.out.println("Products saved to " + fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void displayMenu() {
        Scanner scanner = new Scanner(System.in);
        int choice;
        do {
            System.out.println("Please choose an option:");
            System.out.println("1. Display products");
            System.out.println("2. Find highest and lowest priced products");
            System.out.println("3. Add a product");
            System.out.println("4. Remove a product");
            System.out.println("5. Save and exit");
            System.out.println("6. Filter top 3 most expensive food products");
            System.out.println("0. Exit");
            try {
                choice = scanner.nextInt();
                scanner.nextLine(); // Consume new line character
                switch (choice) {
                    case 1:
                        displayProducts();
                        break;
                    case 2:
                        findHighestAndLowestPricedProducts();
                        break;
                    case 3:
                        addProduct(scanner);
                        break;
                    case 4:
                        removeProduct(scanner);
                        break;
                    case 5:
                        saveProducts();
                        System.out.println("Exiting...");
                        return;
                    case 6:
                        filterTop3ExpensiveFoodProducts();
                        break;
                    case 0:
                        System.out.println("Exiting...");
                        return;
                    default:
                        System.out.println("Invalid choice. Please try again.");
                }
            } catch (InputMismatchException e) {
                System.out.println("Invalid input. Please try again.");
                scanner.nextLine(); // Clear input
            }
        } while (true);
    }

    private static void displayProducts() {
        products.stream()
                .sorted(Comparator.comparingInt(Product::getId))
                .forEach(System.out::println);
    }

    private static void findHighestAndLowestPricedProducts() {
        Optional<Product> highestPriceProduct = products.stream()
                .max(Comparator.comparingDouble(Product::getPrice));
        Optional<Product> lowestPriceProduct = products.stream()
                .min(Comparator.comparingDouble(Product::getPrice));

        System.out.println("Highest price product: " + highestPriceProduct.orElse(null));
        System.out.println("Lowest price product: " + lowestPriceProduct.orElse(null));
    }

    private static void addProduct(Scanner scanner) {
        int id;
        String name;
        String category;
        double price;
        do {
            System.out.print("Enter product id: ");
            id = scanner.nextInt();
            scanner.nextLine(); // Consume new line character
        } while (isProductIdExists(id));

        System.out.print("Enter product name: ");
        name = scanner.nextLine();

        System.out.print("Enter product category: ");
        category = scanner.nextLine();

        System.out.print("Enter product price: ");
        price = scanner.nextDouble();

        Product product = new Product(id, name, category, price);
        products.add(product);
        System.out.println("Product added successfully.");
    }

    private static boolean isProductIdExists(int id) {
        for (Product product : products) {
            if (product.getId() == id) {
                System.out.println("Product id already exists. Please enter a different id.");
                return true;
            }
        }
        return false;
    }

    private static void removeProduct(Scanner scanner) {
        System.out.print("Enter product id to remove: ");
        int id = scanner.nextInt();

        Iterator<Product> iterator = products.iterator();
        boolean found = false;
        while (iterator.hasNext()) {
            Product product = iterator.next();
            if (product.getId() == id) {
                iterator.remove();
                found = true;
                break;
            }
        }

        if (found) {
            System.out.println("Product removed successfully.");
        } else {
            System.out.println("Product not found.");
        }
    }

    private static void filterTop3ExpensiveFoodProducts() {
        products.stream()
                .filter(p -> p.getCategory().equalsIgnoreCase("food"))
                .sorted(Comparator.comparingDouble(Product::getPrice).reversed())
                .limit(3)
                .forEach(System.out::println);
    }
}

注意事项:

  1. 商品类Product需要实现Serializable接口,以支持序列化和反序列化。
  2. 代码中提供了一个product.ser文件用于保存集合数据,如果product.ser文件不存在,之后的操作会创建这个文件。