设计Appliances类包含品牌brand和电器的价格price。定义getter/setter方法,brand要求品牌至少4位,否则抛出异常,价格price要求价格必须大于等于0, 否则抛出异常,定义测试类Test, 利用File类建立goodsInfo.txt文件,利用BufferedWriter(缓冲流)+ FileWriter(字符流)将商品信息存入goodsInfo.txt文件,利用BufferedReader+FileReader读取文件内容,在屏幕显示。
时间: 2024-03-03 11:49:13 浏览: 47
下面是Appliances类的代码实现:
```java
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("品牌至少4位!");
}
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) throws Exception {
if (price < 0) {
throw new Exception("价格必须大于等于0!");
}
this.price = price;
}
}
```
下面是Test类的代码实现:
```java
import java.io.*;
public class Test {
public static void main(String[] args) {
Appliances[] appliances = new Appliances[3];
appliances[0] = new Appliances();
appliances[1] = new Appliances();
appliances[2] = new Appliances();
try {
appliances[0].setBrand("Haier");
appliances[0].setPrice(2399.00);
appliances[1].setBrand("Midea");
appliances[1].setPrice(1999.00);
appliances[2].setBrand("Gree");
appliances[2].setPrice(2899.00);
} catch (Exception e) {
e.printStackTrace();
}
File file = new File("goodsInfo.txt");
try {
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
for (Appliances appliance : appliances) {
bw.write(appliance.getBrand() + "," + appliance.getPrice());
bw.newLine();
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
运行Test类后,可以在控制台上看到输出结果:
```
Haier,2399.0
Midea,1999.0
Gree,2899.0
```
同时,也会在项目目录下生成一个名为“goodsInfo.txt”的文件,其中存储了商品信息。
阅读全文