楼主以后编程的,一定要注意变量名要规范,一定要有意义,
不要用O这中单个字母来当变量
import java.lang.*;public class CompareCircle {
public static void main(String[] args) {
float[] p = new float[6];
System.out.println("输入两个圆的属性,圆心X坐标,圆心Y坐标,半径:");
for (int i = 0; i < 6; i++) {
java.util.Scanner sc = new java.util.Scanner(System.in);
p[i] = sc.nextFloat();
}
Point p1 = new Point(p[0], p[1]);
Point p2 = new Point(p[3], p[4]);
Circle c1 = new Circle(p[2], p1);
Circle c2 = new Circle(p[5], p2);
Compare cmp = new Compare(c1, c2);
cmp.GetRelationship();
}
}class Point {
float fX, fY; Point() {
}; Point(float fx, float fy) {
fX = fx;
fY = fy;
} void Set(float fx, float fy) {
fX = fx;
fY = fy;
} float GetX() {
return fX;
} float GetY() {
return fY;
}
}class Circle {
float fR; // 半径
Point O; // 圆心 Circle() {
}; Circle(float r, Point o) {
fR = r;
// O.Set(o.GetX(), o.GetY());
this.O = o;
} Point GetO() {
return O;
} float GetR() {
return fR;
} void Set(float r, Point o) {
fR = r;
O.Set(o.GetX(), o.GetY());
}
}class Compare {
Circle c1, c2;
double d; // 圆心距 Compare(Circle a, Circle b) {
// c1.Set(a.GetR(), a.GetO());
// c2.Set(b.GetR(), b.GetO());

this.c1=a;
this.c2=b;
d = Math.sqrt(Math.pow((a.GetO().GetX() - b.GetO().GetX()), 2)
+ Math.pow((a.GetO().GetY() - b.GetO().GetY()), 2));
} float GetLargeR() // 获取较大的圆半径
{
if (c1.GetR() > c2.GetR()) {
return c1.GetR();
} else {
return c2.GetR();
}
} float GetSmallR() // 获取较小的圆半径
{
if (c1.GetR() < c2.GetR()) {
return c1.GetR();
} else {
return c2.GetR();
}
} void GetRelationship() {
if (d < (GetLargeR() - GetSmallR())) {
System.out.printf("小圆在大圆内。");
return;
}
if (d < (GetLargeR() + GetSmallR())) {
System.out.printf("两圆重叠。");
return;
}
System.out.printf("两圆相离。");
}
}

解决方案 »

  1.   

    class Circle {
    float fR; // 半径
    Point O; // 圆心 Circle() {
    }; Circle(float r, Point o) {
    fR = r;
    O.Set(o.GetX(), o.GetY());
    this.O = o;
    } Point GetO() {
    return O;
    } float GetR() {
    return fR;
    } void Set(float r, Point o) {
    fR = r;
    O.Set(o.GetX(), o.GetY());
    }
    }这里的 Point O; // 圆心 O所指向的对象还是null,所以不能在后面直接调用方法 O.Set(o.GetX(), o.GetY());
    你需要先new Point对象
      

  2.   


    谢谢,那么使用this以后就默认new了一个Point对象O了吗?
      

  3.   


    谢谢,那么使用this以后就默认new了一个Point对象O了吗?
    另外我之所以之前会那么样写是因为我怕直接以Point对象赋值会报错,因为我之前是学C++的,这种时候在C++里这个自定义类的赋值操作符“=”应该是需要重载的,难道JAVA里不用的,那么方便??
      

  4.   


    谢谢,那么使用this以后就默认new了一个Point对象O了吗?
    另外我之所以之前会那么样写是因为我怕直接以Point对象赋值会报错,因为我之前是学C++的,这种时候在C++里这个自定义类的赋值操作符“=”应该是需要重载的,难道JAVA里不用的,那么方便??我没学过C++,不知道那什么情况
    关于this.O=o,小写o指的是参数传入的对象引用,就是将O指向参数传入的小o这个对象
    你的程序18、19二行        
            Circle c1 = new Circle(p[2], p1);
      这里this.O就指向了p1这个对象
                    Circle c2 = new Circle(p[5], p2);
     这里this.O就指向了p2这个对象
      

  5.   

    根据 thinking in java的规范,不要滥用 this,其实两个名称不一样,可以不使用this,this在给成员变量赋值的时候,很多是应该 传递过来的实参和本类中的成员变量名称相同才用.不要什么地方都用.