gpt4 book ai didi

java - 形状对象不接受输入的坐标

转载 作者:行者123 更新时间:2023-12-01 13:12:35 25 4
gpt4 key购买 nike

我的一项作业遇到了问题。我必须创建自己的 ShapeCircleRectangle 类。问题是,当将 Point 对象输入到圆形和矩形时,Shape 类不会在新形状对象的构造函数中接受它。

所以当我运行主程序时,圆心和矩形顶角的坐标为空,而不是输入的坐标。

如何让 Shape 接受点坐标?

(如果代码/术语有误,我很抱歉,我对 Java 还很陌生)

我的形状类别:

public class Shape {
private int sides;
private Color colour;
private Point coordinates;

public Shape (int sides, Point coordinates, Color colour) {
this.sides = sides;
this.colour = colour;
this.coordinates = coordinates;
}

我的圈子类(class):

public class Circle extends Shape {
private Point center;
private int radius;

//constructor for circle class
public Circle(Point center, int radius, Color c) {
super(0, center, c);
this.radius = radius;

我的矩形类:

public class Rectangle extends Shape {

private int sides = 4;
private Point topCorner;
private int width, length;

//Constructor for rectangle
public Rectangle(Point topCorner, int width, int length, Color c) {
super(4, topCorner, c);
this.width = width;
this.length = length;
}

我的主要类(class):

    public static void main(String[] args) {
Point p1 = new Point(0,20);
Point p2 = new Point(20,0);
Point p3 = new Point(30,30);

Shape r = new Rectangle(p1, 10, 15, Color.BLUE);
Shape c = new Circle (p3, 25, Color.YELLOW);

最佳答案

这是因为您从未初始化topCornercenter

在您的 Circle 构造函数中,添加

this.center = center;

在您的 Rectangle 构造函数中,添加

this.topCorner = topCorner;

但是,说实话,centertopCorner 的用途是什么? Shape#coordinates 将是您要查找的坐标。当可以从父类(super class)访问它时,无需在子类中创建另一个 Point 对象。

关于java - 形状对象不接受输入的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22739255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com