我编写了一个Java程序,用于计算两个给定圆的位置关系。
我里面有3个类,其中Circle类中有个属性是Point类对象,而javac编译通过,但在运行时提示这句出错,也就是Circle的构造函数出错(代码的第40行左右),初学JAVA,可能是犯了很基础的错误,求指教~
完整代码如下:
package homework.experiment_02.Circle;
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());}
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());
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("两圆相离。");
}
}
------解决方案--------------------
楼主以后编程的,一定要注意变量名要规范,一定要有意义,
不要用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;