圆类:
/*
@author XiHai ShengGe
*/
//对类进行序列化
public class Circle implements Serializable {
private static final long serialVersionUID = 1L;
private int r;
public Circle() {
}
public Circle(int r) {
this.r = r;
}
public int getR() {
return r;
}
public void setR(int r) {
this.r = r;
}
@Override
public String toString() {
return "圆(" +
+ r +
")";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Circle circle = (Circle) o;
return r == circle.r;
}
}
测试类
/*
@author XiHai ShengGe
*/
public class CircleTest {
public static void main(String[] args){
File f1 = new File("E:/temp/circle.txt");
Random rand = new Random();
ObjectOutputStream fw = null;
ObjectInputStream ois = null;
try {
fw = new ObjectOutputStream(new FileOutputStream(f1));
//为啥循环次数只有设置的数字的一半
for (int j = 0; j < 11; j++) {
int i = rand.nextInt(100);
Circle c = new Circle(i);
fw.writeObject(c);
}
ois = new ObjectInputStream(new FileInputStream(f1));
while (ois.readObject() != null) {
Circle c = (Circle) ois.readObject();
if (c.getR() != 0){
System.out.println("半径为"+ c.getR() +"的圆,面积为" + (c.getR()) * (c.getR()) * Math.PI);
}else {
//boolean flag =
throw new MyException("半径不能为0");
}
}
ois.close();
fw.close();
}catch(EOFException e){
System.out.println("读写完毕!");
} catch (MyException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
异常类,也可以把它放到圆类中
/*
@author XiHai ShengGe
*/
public class MyException extends Exception{
//提供无参数构造方法
public MyException() {
}
//提供有参数构造方法
public MyException(String message) {
super(message);
}
}
在这里我也遇到一个问题,在循环添加圆对象的时候,循环次数会减半,望看到的大佬解惑