1. 封装猫粮类
public class CatFood {
    private String name;
    private double price;
    private int weight;

    public CatFood(String name, double price, int weight) {
        this.name = name;
        this.price = price;
        this.weight = weight;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    public int getWeight() {
        return weight;
    }

    public double getTotalPrice() {
        return price * weight;
    }
}
  1. 创建猫粮对象并存储到 HashSet 集合中
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        Set<CatFood> catFoods = new HashSet<>();

        CatFood catFood1 = new CatFood("Whiskas", 10.5, 5);
        CatFood catFood2 = new CatFood("Purina", 8.2, 4);
        CatFood catFood3 = new CatFood("Royal Canin", 15.3, 3);

        catFoods.add(catFood1);
        catFoods.add(catFood2);
        catFoods.add(catFood3);
    }
}
  1. 输出购物信息并求出总价
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        Set<CatFood> catFoods = new HashSet<>();

        CatFood catFood1 = new CatFood("Whiskas", 10.5, 5);
        CatFood catFood2 = new CatFood("Purina", 8.2, 4);
        CatFood catFood3 = new CatFood("Royal Canin", 15.3, 3);

        catFoods.add(catFood1);
        catFoods.add(catFood2);
        catFoods.add(catFood3);

        for (CatFood catFood : catFoods) {
            System.out.println("猫粮名称:" + catFood.getName());
            System.out.println("猫粮价格:" + catFood.getPrice() + " 元/袋");
            System.out.println("猫粮重量:" + catFood.getWeight() + " kg");
            System.out.println("猫粮总价:" + catFood.getTotalPrice() + " 元");
            System.out.println();
        }

        double totalPrice = catFoods.stream()
                .mapToDouble(CatFood::getTotalPrice)
                .sum();
        System.out.println("三种猫粮的总价为:" + totalPrice + " 元");
    }
}

输出结果:

猫粮名称:Purina
猫粮价格:8.2 元/袋
猫粮重量:4 kg
猫粮总价:32.8 元

猫粮名称:Royal Canin
猫粮价格:15.3 元/袋
猫粮重量:3 kg
猫粮总价:45.900000000000006 元

猫粮名称:Whiskas
猫粮价格:10.5 元/袋
猫粮重量:5 kg
猫粮总价:52.5 元

三种猫粮的总价为:131.2 元
``
分析 1 使用封装定义猫粮类 2 创建 3 个猫粮对象存储到 HashSet 集合中 3 输出 3 条购物信息并求出 3 种猫粮的总价

原文地址: https://www.cveoy.top/t/topic/eFT5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录