Java:如何将点值传递给折线?

标签 java arrays oop polyline

所以我有这个 Polyline 类,它使用另一个类 (Point) 来创建折线。

Point仅定义一个具有x和y值的点及其名称(Point A、Point B等)

public class Polyline 

{
private Point []    corner;

public Polyline ()
{
    this.corner = new Point[0];

}

public Polyline (Point [] corner)
{
    this.corner = new Point [cornerlength];
    for (int i = 0; i < corner.length; i++)
        this.corner[i] = new Point (corner[i]);

}

现在我的问题是,如何赋予这些角它们的值?我制作了一个名为 PolylineTest 的程序,我想给它一些值并将其打印出来,但我还没有弄清楚如何做到这一点。

我想它会是这样的:

Polyline [] p1 = new Polyline[0];

但我不知道如何给它一个值。

有人能给我一个正确的方向吗?

提前谢谢

(代码目前无法编译)

最佳答案

假设您的 Point 类如下所示:

public class Point {

    public String name;
    public int x;
    public int y;

    public Point(String name, int x, int y) {
        this.name = name;
        this.x = x;
        this.y = y;
    }

    public Point(Point p) {
        this.name = p.name;
        this.x = p.x;
        this.y = p.y;
    }

    public String toString() {
        return name + "[" + x + ", " + y + "]";
    }
}

然后将此方法添加到您的 Polyline 类中:

public String toString() {
    return "Polyline " + Arrays.toString(corner);
}

用法如下:

public class PolylineTest {

    public static void main(String[] args) {
        Point[] points = new Point[] {
                new Point("A", 4, 2),
                new Point("B", 8, 5),
                new Point("C", 1, 7)
        };
        Polyline polyline = new Polyline(points);
        System.out.println(polyline);
    }
}

关于Java:如何将点值传递给折线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20724525/

相关文章:

java - Java中是否有等效于memcpy()的方法?

Mysql使用连接和数组匹配

arrays - 是否必须为字符数组的初始化提供 '\0'?

python - 类变量无法对实例变量执行属性查找

java - 如何创建一个扩展其他两个接口(interface)的接口(interface)来定义java中的类型

javascript - 为什么对象的属性未定义?

java - 我如何转换 xsd : pattern in java regex

不支持 java.util.Date

java - hibernate 异常: Illegal attempt to dereference a collection

c - 为什么这不会打印?