所以我有这个 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/