基础题(每道题约 3~5 分钟) (1) 创建商品类型枚举,食品、电子产品 (2) 创建商品类:商品名称、价格、进货时间、商品类型(枚举类型) 综合题(每道题约 5~7 分钟) (3) 创建管理类完成对集合的增删改查操作 1) 创建集合存入商品,泛型正确 2)创建添加方法: i. 将商品添加到集合中 ii. 使用集合处理如果商品名称和价格相同不能添加到集合中 3) 创建修改方法,根据商品名称,将价格打 9 折 4) 创建查询方法,使用迭代器显示所有商品信息,能正常输出商品类型 5)
时间: 2023-11-28 11:51:39 浏览: 35
基础题:
(1) 商品类型枚举的创建:
```
public enum ProductType {
FOOD,
ELECTRONICS
}
```
(2) 商品类的创建:
```
public class Product {
private String name;
private double price;
private Date purchaseDate;
private ProductType type;
public Product(String name, double price, Date purchaseDate, ProductType type) {
this.name = name;
this.price = price;
this.purchaseDate = purchaseDate;
this.type = type;
}
// getters and setters
}
```
综合题:
(3) 商品管理类的创建:
```
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ProductManager {
private List<Product> products = new ArrayList<>();
// 添加商品
public void addProduct(Product product) {
// 判断商品是否已经存在
for (Product p : products) {
if (p.getName().equals(product.getName()) && p.getPrice() == product.getPrice()) {
return;
}
}
products.add(product);
}
// 修改商品价格
public void updateProduct(String name) {
for (Product p : products) {
if (p.getName().equals(name)) {
p.setPrice(p.getPrice() * 0.9);
}
}
}
// 查询所有商品信息
public void showProducts() {
Iterator<Product> iterator = products.iterator();
while (iterator.hasNext()) {
Product p = iterator.next();
System.out.println("Name: " + p.getName() + ", Price: " + p.getPrice() + ", Type: " + p.getType());
}
}
}
```
在这个商品管理类中,我们使用了一个集合来存储商品信息。在添加商品时,我们先判断集合中是否已经存在同名同价商品,如果是则不进行添加操作。在修改商品价格时,我们通过传入商品名称来找到对应的商品,并将其价格打 9 折。在查询商品信息时,我们使用迭代器遍历集合,并输出商品的名称、价格和类型。
注意:上述代码没有包含 setter 和 getter 方法,需要自行添加。