gpt4 book ai didi

java - 表达式的类型必须是数组类型,但它被解析为 ArrayList

转载 作者:行者123 更新时间:2023-12-01 13:23:43 25 4
gpt4 key购买 nike

我试图找出从面积方法调用数组的正确方法,然后应该计算给定点的面积。不确定从每个数组中选择特定 x 和 y 坐标的正确方法是什么。

MyPolygon 类

  import java.util.ArrayList;
import java.awt.geom.Point2D;
import java.awt.geom.Point2D.Double;

/**
* A class that represents a geometric polygon. Methods are provided for adding
* a point to the polygon and for calculating the perimeter and area of the
* polygon.
*/
class MyPolygon {

// list of the points of the polygon
private ArrayList<Point2D.Double> points;

/**
* Constructs a polygon with no points in it.
*/
public MyPolygon() {
points = new ArrayList<Point2D.Double>();
}

/**
* Adds a point to the end of the list of points in the polygon.
*
* @param x
* The x coordinate of the point.
* @param y
* The y coordinate of the point.
*/
public void add(double x, double y) {
points.add(new Point2D.Double(x, y));
}

/**
* Calculates and returns the perimeter of the polygon.
*
* @return 0.0 if < 2 points in polygon, otherwise returns the sum of the
* lengths of the line segments.
*/
public double perimeter() {

if (points.size() < 2) {
return 0.0;
}

int i = 0;
double d = 0;
double total = points.get(0).distance(points.get(points.size() - 1));

while (i < points.size() - 1) {
Point2D.Double point1 = points.get(i);
// double x = point1.x;
// double y = point1.y;
Point2D.Double point2 = points.get(i + 1);
// double x1 = point2.x;
// double y1 = point2.y;

d = point1.distance(point2);
// d = Math.sqrt(Math.pow(x1 - x,2) + Math.pow(y1 - y, 2));

total = total + d;
i++;

}
return total;

}

/**
* Calculates and returns the area of the polygon.
*
* @return 0.0 if < 3 points in the polygon, otherwise returns the area of
* the polygon.
*/
public double area() {

int i = 0;
double a = 0;
double total = 0;
total = total + a;

if (points.size() < 3) {
return 0.0;
}

for (int m = 0; m < points.size(); m++) {

total = total + (points[m].x() * points[m + 1].y()) - (points[m].y() * points[m + 1].x());
}
return 0.5 * total;
}

}

测试员类

class PolygonTester {

public static void main(String args[]) {
MyPolygon poly = new MyPolygon();
poly.add(1.0,1.0);
poly.add(3.0,1.0);
poly.add(1.0,3.0);
System.out.println(poly.perimeter());
System.out.println(poly.area());
}

}

最佳答案

你的标题实际上已经是解决方案了。您使用 points[m] 这是数组表示法。但点不是数组。这是一个 list 。使用 points.get(int i) 代替,就像在 perimeter() 中所做的那样。

关于java - 表达式的类型必须是数组类型,但它被解析为 ArrayList<Point2D.Double>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21896242/

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