用Java创建一个圆圈

时间:2016-02-24 01:09:33

标签: java class geometry

我正在尝试用Java创建一个圆形类。 我粘贴了代码的第一部分,但我想我可能会丢失 课上的东西?

public class Circle {

    /*
     * Here, you should define private variables that represent the radius and
     * centre of this particular Circle. The radius should be of type double,
     * and the centre should be of type Point.
     */
    private Point A = new Point();
    private double radius;
    // =========================
    // Constructors
    // =========================
    /**
     * Default constructor - performs no initialization.
     */
    public Circle() {
        // This method is complete.
    }

    /**
     * Alternative constructor, which sets the circle up with x and y
     * co-ordinates representing the centre, and a radius. Remember you should
     * not store these x and y co-ordinates explicitly, but instead create a
     * Point to hold them for you.
     *
     * @param xc   x-coordinate of the centre of the circle
     * @param yc   y-coordinate of the centre of the circle
     * @param rad  radius of the circle
     */
    public Circle(double xc, double yc, double rad) {
        Point centre = new Point(xc,yc);
        radius=rad;
    }

    public Circle(Point center, double rad) {

      center = Center;
      radius = Rad;
    }

1 个答案:

答案 0 :(得分:0)

代表中心的私人变量名为A(这不是一个好名字,为什么不称之为center)。

在您实现的第一个构造函数中,您正在定义一个局部变量Point centre并为其分配坐标。实际上你想把它们分配给类变量(我假设你已经重命名了它):

center = new Point(xc,yc);

在第二个构造函数中,您尝试将类分配给不应编译的变量。您分配的变量也是参数,而不是类属性(具有相同的名称)。

您可以使用:

public Circle(Point center, double rad) {

  this.center = center;
  this.radius = rad;
}

this告诉Java您正在引用类变量而不是具有相同名称的本地变量。