圆的相关写法

设计一个Circle 类,其属性为圆心点(类型为前面设计的类 MyPoint)和半径,并为此类编写以下三个方法:
一是计算圆面积的 calArea()方法;
二是计算周长的 calLength();
三是 boolean inCircle(MyPoint mp)方法,功能是测试作为参数的某个点是否在当前对象圆内(圆内,包括圆上返回 true;在圆外,返回false。

//写一个 MyPoint 完全封装类法
public class MyPoint {
    private int x;
    private int y;

    //构造器
    public MyPoint(int x, int y) {
        this.setX(x);
        this.setY(y);
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getX() {
        return x;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getY() {
        return y;
    }

    public String toString() {
        return "(" + x + "," + y + ")";
    }
}
public class Circle {
    MyPoint center;//圆心
    int r; //半径

    public double calArea() {  //calArea:面积
        return Math.PI * r * r;
    }

    public double callength() { //calLength:周长
        return Math.PI * r * 2;
    }

    boolean inCircle(MyPoint mp) {
        double d = Circle1.getLength(mp, center); //mp:传入的点
        if (d > r) {
            return false;
        } else {
            return true;
        }
    }
}
public class Circle1 {
    public static double getLength(MyPoint m1, MyPoint m2) {
        int cx = m1.getX() - m2.getX(); //两点x的距离
        int cy = m1.getY() - m2.getY(); //两点y的距离
        return Math.sqrt(cx * cx + cy * cy); //两点的长度
    }
}
public class CircleTest {
    public static void main(String[] args) {
        Circle c = new Circle();
        MyPoint m = new MyPoint(5, 5);
        c.center = m; //圆心
        c.r = 10;  //半径
        System.out.println(c.calArea()); //面积
        System.out.println(c.callength()); //周长

        MyPoint mp = new MyPoint(15, 115);
        boolean b = c.inCircle(mp);
        System.out.println(b);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值