2014-02-19 166 views
0

我有一個稱爲周長的方法,該方法應該在某些點上採用並根據提供的點返回多邊形的周長。當我使用測試儀運行程序時,我總是得到錯誤的外圍答案。用Java計算多邊形的周長

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; 

    } 

} 

的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

什麼是你得到錯誤的答案?你期望它是什麼? – mdewitt

+6

你忘記了回到開始的邊緣嗎? – ajb

+0

我應該越來越6.82842712474619 – user3308067

回答

1

你應該初始化變量總額與去年邊緣的長度:

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