题目要求:
(1) 设计一个类代表二维空间的一个点
(2) 设计一个类代表二维空间的一个圆。要求两个成员变量。一个是圆心,一 个是半径,提供计算面积的方法。
(3) 为上述Cricle类添加一个方法,计算一个点(Point对象)是否在圆(Cricle对象)内,并写程序验证
public class Main {
public static void main(String[] args) {
Cricle1 c = new Cricle1(0, 0, 3) ; //传入圆心与半径
//求面积
System.out.println("圆的面积为:"+c.size());
//判断一点是否在圆内
if(c.isIn(2, 2))
System.out.println("在圆内");
else
System.out.println("不在圆内");
}
}
class Cricle1{
double x1 , y1 , r ; //分别代表圆心的两坐标与圆的半径
public Cricle1(double x1, double y1, double r) {
super();
this.x1 = x1;
this.y1 = y1;
this.r = r;
}
public double size () {//求面积,传半径作为参数
return Math.PI*r*r;
}
public boolean isIn (double x2 , double y2) {//判断点是否在圆内,传入随便一点的坐标
if( Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2) >= Math.pow(r, 2))
return false ;
else
return true ;
}
}
对于上面的代码,你是否感觉到一丝错意呢?
没错,上面的代码没有按照题目中给出的要求定义一个Point的类来做
而之所以将上面的代码摆上去,是因为除了没有定义Point类外,运算步骤都是正确的没有任何问题的,可以将上面的代码作为一种解题思路,在以后能够更好的变通
下面给出正确的代码:
public class Text_1_1 {
public static void main(String[] args) {
Point p1 = new Point(0, 0);
Point p2 = new Point(2, 0);
Cricle c = new Cricle() ;
c.setP1(p1);//圆心
c.setP2(p2);//随便一点
c.setR(2);//半径
c.sum();//面积
c.inOrOut();//是否在圆内
}
}
class Point{
private double x,y;//点的坐标
public Point(double x, double y) {
super();
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
}
class Cricle {
Point p1 ; // 圆心
Point p2 ; // 随便一点
private double r ;//半径
public void sum () {//求圆面积
System.out.println("圆的面积为:"+Math.PI*r*r);
}
public void inOrOut () {//判断一点是否在圆内
if( Math.pow( p1.getX()-p2.getX() , 2) + Math.pow( p1.getY()-p2.getY() , 2 ) >= Math.pow(r, 2))
System.out.println("不在圆内");
else
System.out.println("在圆内");
}
public Point getP1() {
return p1;
}
public void setP1(Point p1) {
this.p1 = p1;
}
public Point getP2() {
return p2;
}
public void setP2(Point p2) {
this.p2 = p2;
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
}
是不是今天有涨知识了呢?