我有一个叫做周长的方法,它应该接收一些点并根据提供的点返回多边形的周长。当我使用测试仪运行程序时,我一直得到错误的外围答案。
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 = 0;
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);
System.out.println(d);
//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() {
return 0;
}
}
The Tester类:
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());
}
}
答案 0 :(得分:1)
你应该用最后边缘的长度初始化总变量:
double total = points.get(0).distance(poinsts.get(points.size() - 1));