我有一個名爲SimplePolygon的類,它創建一個由用戶提供座標的多邊形。我正在嘗試定義一種計算多邊形面積的方法。這是一項任務,課程講師希望我們使用以下公式來計算面積。Java中多邊形的計算區域
我可以使用任一式。我選擇了正確的一個。
我的代碼給了我錯誤的地方。我不知道什麼是錯的。
public class SimplePolygon implements Polygon {
protected int n; // number of vertices of the polygon
protected Point2D.Double[] vertices; // vertices[0..n-1] around the polygon
public double area() throws NonSimplePolygonException {
try
{
if(isSimple()==false)
throw new NonSimplePolygonException();
else
{
double sum = 0;
for(int i = 0; i < vertices.length - 1; i++)
if(i == 0)
sum += vertices[i].x * (vertices[i+1].y - vertices[vertices.length - 1].y);
else
sum += vertices[i].x * (vertices[i+1].y - vertices[i-1].y);
double area = 0.5 * Math.abs(sum);
return area;
}
}
catch(NonSimplePolygonException e)
{
System.out.println("The Polygon is not simple.");
}
return 0.0;
}
以下是測試儀代碼。多邊形與區域2的長方形,但輸出爲2.5
Point2D.Double a = new Point2D.Double(1,1);
Point2D.Double b = new Point2D.Double(3,1);
Point2D.Double c = new Point2D.Double(3,2);
Point2D.Double d = new Point2D.Double(1,2);
SimplePolygon poly = new SimplePolygon(4);
poly.vertices[0] = a;
poly.vertices[1] = b;
poly.vertices[2] = c;
poly.vertices[3] = d;
System.out.println(poly.area());
請向我們提供的樣本數據和預期的輸出。 – Compass 2014-09-23 05:25:52
'isSimple()'方法來自哪裏? – 2014-09-23 05:28:41