设计Appliances类包含品牌brand和电器的价格price。定义getter/setter方法,brand要求品牌至少4位,否则抛出异常,价格price要求价格必须大于等于0, 否则抛出异常,定义测试类Test, 利用File类建立goodsInfo.txt文件,利用BufferedWriter(缓冲流)+ FileWriter(字符流)将商品信息存入goodsInfo.txt文件,利用BufferedReader+FileReader读取文件内容,在屏幕显示。
时间: 2024-03-03 20:49:05 浏览: 116
好的,我来解答这个问题。
首先,我们需要定义一个Appliances类,包含品牌brand和价格price两个属性,并实现它们的getter和setter方法。其中,setter方法需要在输入参数不合法时抛出异常。代码如下:
```java
public class Appliances {
private String brand;
private double price;
public String getBrand() {
return brand;
}
public void setBrand(String brand) throws IllegalArgumentException {
if (brand.length() < 4) {
throw new IllegalArgumentException("Invalid brand name!");
}
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) throws IllegalArgumentException {
if (price < 0) {
throw new IllegalArgumentException("Invalid price!");
}
this.price = price;
}
}
```
接下来,我们需要编写一个测试类Test,利用File类建立goodsInfo.txt文件,并将商品信息存入文件中。代码如下:
```java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
Appliances[] goods = new Appliances[3];
goods[0] = new Appliances();
goods[0].setBrand("Samsung");
goods[0].setPrice(3999.99);
goods[1] = new Appliances();
goods[1].setBrand("LG");
goods[1].setPrice(2999.99);
goods[2] = new Appliances();
goods[2].setBrand("Sony");
goods[2].setPrice(4999.99);
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("goodsInfo.txt"));
for (Appliances good : goods) {
writer.write(good.getBrand() + " " + good.getPrice() + "\n");
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
最后,我们需要读取goodsInfo.txt文件,并在屏幕上显示其中的内容。代码如下:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
Appliances[] goods = new Appliances[3];
goods[0] = new Appliances();
goods[0].setBrand("Samsung");
goods[0].setPrice(3999.99);
goods[1] = new Appliances();
goods[1].setBrand("LG");
goods[1].setPrice(2999.99);
goods[2] = new Appliances();
goods[2].setBrand("Sony");
goods[2].setPrice(4999.99);
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("goodsInfo.txt"));
for (Appliances good : goods) {
writer.write(good.getBrand() + " " + good.getPrice() + "\n");
}
writer.close();
BufferedReader reader = new BufferedReader(new FileReader("goodsInfo.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这样就完成了这个问题的解答,希望能帮助到你!
阅读全文