gpt4 book ai didi

java - 要点列表+构造函数和方法问题

转载 作者:行者123 更新时间:2023-12-01 04:44:30 28 4
gpt4 key购买 nike

因此,对于这个项目,我希望输入一个包含多个点的数组。 (没有具体数字)。我对如何处理方法和构造函数感到困惑,因为某些方法需要更改,例如获取 X 或 Y 值的平均值。我是否以正确的方式处理这个项目?我应该使用点列表的克隆,还是数组列表或什么...(注意我仅显示 PolygonImpl 类的一部分作为示例,它们的功能都类似)类点包含:

public class Point {

private double x;
private double y;

public Point(double x, double y) {
this.x = x;
this.y = y;
}

public double getX() {
return x;
}

public double getY() {
return y;
}

public Point translate(double dx, double dy) {
return new Point(x+dx, y+dy);
}

public double distanceTo(Point p) {
return Math.sqrt((p.x - x)*(p.x -x) + (p.y-y)*(p.y-y));
}

}

public class PolygonImpl implements Polygon {

private double xSum=0;
private double ySum=0;
private ArrayList<Point> points;
private Point[] pList;
private Point a;

PolygonImpl(Point[] pList) {

this.pList = pList.clone();
points = new ArrayList<Point>();

for (int index = 0; index < pList.length; index++) {
points.add(pList[index]);
xSum += pList[index].getX();
ySum += pList[index].getY();


}
}



public Point getVertexAverage() {
double xSum = 0;
ArrayList<Point> vlist = new ArrayList<Point> ();
double ySum = 0;
for (int index = 0; index < vlist.size(); index++) {
xSum = xSum + vlist.get(index).getX();
ySum = ySum + vlist.get(index).getY();
}

return new Point(xSum/getNumSides(), ySum/getNumSides());
}

public int getNumSides() {
return pList.length;
}

public void move(Point c) {
Point newCentroid = new Point(a.getX()+ c.getX(), a.getY() +c.getY());


}

public void scale(double factor) {

ArrayList<Point> points = new ArrayList<Point> ();

for (int index = 0; index < pList.length; index++) {
{ double x = pList[index].getX() *factor;
double y = pList[index].getY() * factor;
Point a = new Point(x,y);
points.add(index,a);

}
}
}

最佳答案

在这种情况下,我认为您不需要额外的 List 对象;它们是多余的。这是仅使用 pList 数组的代码。

public class PolygonImpl implements Polygon {

private double xSum=0;
private double ySum=0;
private Point[] pList;
private Point a;

PolygonImpl(Point[] pList) {

this.pList = pList.clone();

for (int index = 0; index < pList.length; index++) {
xSum += pList[index].getX();
ySum += pList[index].getY();
}
}



public Point getVertexAverage() {
double xSum = 0;
double ySum = 0;
for (int index = 0; index < pList.length; index++) {
xSum = xSum + pList[index].getX();
ySum = ySum + pList[index].getY();
}

return new Point(xSum/getNumSides(), ySum/getNumSides());
}

public int getNumSides() {
return pList.length;
}

public void move(Point c) {
Point newCentroid = new Point(a.getX()+ c.getX(), a.getY() +c.getY());


}

public void scale(double factor) {
for (int index = 0; index < pList.length; index++)
{
double x = pList[index].getX() *factor;
double y = pList[index].getY() * factor;
Point a = new Point(x,y);
pList[index] = a;

}
}

关于java - 要点列表+构造函数和方法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16065999/

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