计算圆面积(将圆写入文件中并读取)

这是他人提出的问题,在完成这个练习的过程中,我也遇到了很多问题

定义一个圆形类,要求:
1、有一个私有成员变量r;
2、定义两个构造方法(带两个参数、不带参数);
3、定义一组设置存取r的方法;
4、定义两个方法(求面积、求周长);
5、重写toString方法(输出:“圆®”);
6、重写equal方法(当两个圆r相等时为真);
7、自定义异常类,创建圆对象中当圆半径等于零时抛出自定义异常;
8、定义一个测试类完成如下要求:
(1)利用随机方法创建若干圆对象保存到数据文件。
(2)读出文件中所有圆对象并计算输出圆面积最小值。
(3)对可能出现的异常进行处理

下面是代码

圆类
/*
@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 MyException extends Exception{

        //提供无参数构造方法
        public MyException() {
        }

        //提供有参数构造方法
        public MyException(String message) {
            super(message);
        }
}
/*
@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();
        }
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值