设计Appliances类,包含品牌brand和电器的价格price。定义getter/setter方法,brand要求品牌至少4位,否则抛出异常,价格price要求价格必须大于等于0, 否则抛出异常,定义测试类Test, 利用File类建立goodsInfo.xls文件,利用jxl.jar包将商品信息存入goodsInfo.xls文件,实现数据的增删改查。
时间: 2024-03-03 17:49:40 浏览: 72
以下是一个可能的 Java 实现:
```
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
public class Appliances {
private String brand;
private double price;
public String getBrand() {
return brand;
}
public void setBrand(String brand) throws Exception {
if (brand.length() < 4) {
throw new Exception("Brand must be at least 4 characters.");
}
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) throws Exception {
if (price < 0) {
throw new Exception("Price cannot be negative.");
}
this.price = price;
}
public static void main(String[] args) {
List<Appliances> goods = new ArrayList<>();
Appliances a1 = new Appliances();
try {
a1.setBrand("Brand1");
a1.setPrice(100.0);
} catch (Exception e) {
e.printStackTrace();
}
goods.add(a1);
Appliances a2 = new Appliances();
try {
a2.setBrand("Brand2");
a2.setPrice(200.0);
} catch (Exception e) {
e.printStackTrace();
}
goods.add(a2);
File file = new File("goodsInfo.xls");
try {
WritableWorkbook workbook = Workbook.createWorkbook(file);
WritableSheet sheet = workbook.createSheet("Goods", 0);
sheet.addCell(new Label(0, 0, "Brand"));
sheet.addCell(new Label(1, 0, "Price"));
int row = 1;
for (Appliances a : goods) {
sheet.addCell(new Label(0, row, a.getBrand()));
sheet.addCell(new Label(1, row, String.valueOf(a.getPrice())));
row++;
}
workbook.write();
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
// TODO: Implement data modification and retrieval using jxl.jar
}
}
```
这个实现定义了 `Appliances` 类,并包含了 `brand` 和 `price` 字段,以及相应的 getter 和 setter 方法。在 setter 方法中,如果品牌长度小于 4 或价格小于 0,就抛出异常。在 `main` 方法中,创建了两个 `Appliances` 对象,并将它们添加到一个 `ArrayList` 中。然后,使用 `jxl.jar` 库将商品信息写入 Excel 文件 `goodsInfo.xls` 中。最后,需要实现数据修改和检索,这里还没有完成。
阅读全文