package polygongeneric;
import java.util.ArrayList;
public class Polygon {
private ArrayList <Point2d> p = null;
private int points = 0;
public Polygon() { }
public Polygon(int numPoints) {
p = new ArrayList<>();
}
public boolean addPoint(Point2d point) {
p.add(points, point);
points++;
return true;
}
public boolean addPoint(double x, double y) {
Point2d a = new Point2d(x,y);
p.add(points, a);
return true;
}
@Override
public String toString() {
String s = "";
for (int i=0; i<points; i++)
s += p.get(i).toString() + "\n";
return s;
}
}
我正在尝试将一个类从使用对 Point2d 对象的引用数组转换为 Point2d 类型。这是我到目前为止所得到的,但它没有输出它应该输出的答案。
这是我的代码输出
(0.1,0.9)
(0.5,0.5)
(0.2,0.5)
这就是它应该输出的内容
(0.1,0.9)
(0.3,0.7)
(0.5,0.5)
(0.4,0.8)
(0.2,0.5)
你们有什么想法吗?我做错了什么?
这是我的 Point2d 类(class)
package polygongeneric;
public class Point2d {
private double x = 0, y = 0;
public Point2d() { }
public Point2d(double x, double y) {
setX(x);
setY(y);
}
public void setX(double initX) {
if (initX >= 0 && initX <= 1)
x = initX;
}
public void setY(double y) {
if (y >= 0 && y <= 1)
this.y = y;
}
public double getX() { return x; }
public double getY() { return y; }
public String toString() {
return "(" + x + "," + y + ")";
}
}
这是我的主要方法
package polygongeneric;
public class PolygonGeneric {
public static void main(String[] args) {
Polygon p = new Polygon(5);
p.addPoint(new Point2d(.1, .9));
p.addPoint(.3, .7);
p.addPoint(new Point2d(.5, .5));
p.addPoint(.4, .8);
p.addPoint(new Point2d(.2, .5));
System.out.println(p);
}
}
最佳答案
您没有增加 addPoint(double x, double y)
中的位置,所以基本上,您正在用新点替换现有点,因此您丢失了一些点值,您需要更正正确的代码,如下所示:
public boolean addPoint(double x, double y) {
Point2d a = new Point2d(x, y);
p.add(points, a);
points++;
return true;
}
因为您只是将点添加到列表末尾,所以我建议您可以直接使用 arraylist.add(point);
这样您就不会陷入这些增量/其他问题。
此外,您可以按如下方式更改 Polygon 类的构造函数(接受 int
),因为您没有使用 numPoints
变量或者使用 numPoints
的数组作为大小而不是 ArrayList
.
public Polygon() {
p = new ArrayList<>();
}
关于java - 将使用 Point2d 对象引用数组的类转换为使用 java.util.ArrayList<Point2d>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43104345/