简体   繁体   English

用Java计算多边形的周长

[英]Calculating perimeter of a polygon in Java

I have a method called perimeter that is supposed to take in some points and return the perimeter of the polygon based upon the points provided. 我有一种称为“周长”的方法,该方法应该吸收一些点并根据提供的点返回多边形的周长。 I keep getting the wrong answer for perimeter when I use a tester to run the program. 使用测试仪运行程序时,我总是得到错误的外围答案。

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: 测试器类:

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());
    }

}

您应该使用最后一条边的长度初始化总变量:

double total = points.get(0).distance(poinsts.get(points.size() - 1));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM