【问题标题】:Java: How to pass Point values to a Polyline?Java:如何将点值传递给折线?
【发布时间】:2014-01-10 13:11:25
【问题描述】:

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

Point 类只定义了一个带有 x 和 y 值的点及其名称(点 A、点 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];

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

谁能给我一个正确的方向?

提前谢谢你

(代码目前无法编译)

【问题讨论】:

  • 我试过 Polylinje [] p1 = new Polylinje [0]; p1 [0] = {"点 A", 3, 4};但它说数组常量只能用作初始化器
  • 是的,这完全没有意义。强烈建议阅读文档/教程。
  • 另请阅读教程中关于类和构造函数的部分。点不是数组。
  • 其他问题。也许从一本关于 Java 的初学者的书开始会比在计算机中输入随机的东西并期望它们做某事更好的方法。

标签: java arrays oop polyline


【解决方案1】:

假设您的 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);
    }
}

【讨论】:

    猜你喜欢
    • 2010-10-26
    • 2017-05-16
    • 2020-08-08
    • 1970-01-01
    • 2014-01-05
    • 2018-05-17
    • 1970-01-01
    • 2023-03-21
    • 2011-03-21
    相关资源
    最近更新 更多